python - 根据条件重命名 Pandas 数据框的多列

标签 python python-3.x pandas

我有一个 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/

相关文章:

python - 在不创建对象的情况下使用python中类的属性

Python 按日期时间分组

Python:根据*实际*长度填充字符串

python - 查找 Markdown 代码块之外的图像标签

带有被访问键内存的 Python 字典?

python - 正确地将整数与字符串分开(无正则表达式)

python-3.x - 将 pandas 数据框的多列合并为一列

pandas - 如何在 Pandas 时间序列中存储向量?

Pandas 的值(value)计数与多次发生的约束

python - 将 pandas 数据框列转换为嵌套的 python 字典