我有一个 df,我需要在其中将 40 个列名称重命名为空字符串。这可以通过使用 .rename()
来实现,但是我需要在 dict 中提供所有需要重命名的列名。我正在寻找一些更好的方法来通过一些模式匹配来重命名列。在列名中找到 NULL/UNNAMED 的任何地方,将其替换为空字符串。
df1:原始 df(在实际 df 中,我有大约 20 列作为 NULL1-NULL20 和 20 列作为 UNNAMED1-UNNAMED20)
NULL1 NULL2 C1 C2 UNNAMED1 UNNAMED2
0 1 11 21 31 41 51
1 2 22 22 32 42 52
2 3 33 23 33 43 53
3 4 44 24 34 44 54
期望的输出 df:
C1 C2
0 1 11 21 31 41 51
1 2 22 22 32 42 52
2 3 33 23 33 43 53
3 4 44 24 34 44 54
这可以通过
来实现df.rename(columns={'NULL1':'', 'NULL2':'', 'UNNAMED1':'', 'UNNAMED2':''}, inplace=True)
但我不想创建包含 40 个元素的长字典
最佳答案
如果你想坚持使用rename
:
def renaming_fun(x):
if "NULL" in x or "UNNAMED" in x:
return "" # or None
return x
df = df.rename(columns=renaming_fun)
如果映射函数变得更复杂,它会很方便。否则,列表理解会做:
df.columns = [renaming_fun(col) for col in cols]
另一种可能性:
df.columns = map(renaming_fun, df.columns)
但是正如已经提到的,用空字符串重命名不是您通常会做的事情。
关于python - 根据条件重命名 Pandas 数据框的多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55862255/