【问题标题】:Renaming the column names of pandas dataframe is not working as expected - python重命名熊猫数据框的列名没有按预期工作 - python
【发布时间】:2017-11-01 17:58:59
【问题描述】:

我有以下熊猫数据框df。我正在尝试重命名列名,但它没有按预期工作。

代码:

 mapping = {df.columns[0]:'Date', df.columns[1]: 'A', df.columns[2]:'B', df.columns[3]: 'C',df.columns[4]:'D', df.columns[5]: 'E',df.columns[6]:'F', df.columns[7]: 'G',df.columns[8]:'H', df.columns[9]: 'J'}
 df.rename(columns=mapping) 

df.columns 的输出:

MultiIndex(levels=[['A Index', 'B Index', 'C Index', 'D Index', 'E Index', 'F Index', 'G Index', 'H Index', 'I Index', 'J Index', 'K Index', 'L Index', 'M Index', 'N Index', 'O Index', 'date', 'index'], ['PX_LAST', '']],
       labels=[[16, 15, 11, 9, 10, 6, 3, 4, 2, 5, 14, 1, 13, 12, 7, 0, 8], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
       names=['ticker', 'field'])

即使在运行代码之后,列名也保持不变。任何人都可以帮助重命名此数据框的列名。

【问题讨论】:

    标签: python pandas dataframe multiple-columns


    【解决方案1】:

    因为你已经知道列的顺序为什么不直接使用:

    df.columns = ['Date', 'a', 'b', 'c', 'd', 'e', 'f' 'g', 'h', 'i', 'j']
    

    否则,如果您想使用rename,则需要将其分配给变量:

     mapping = {df.columns[0]:'Date', df.columns[1]: 'A', df.columns[2]:'B', df.columns[3]: 'C',df.columns[4]:'D', df.columns[5]: 'E',df.columns[6]:'F', df.columns[7]: 'G',df.columns[8]:'H', df.columns[9]: 'J'}
     df = df.rename(columns=mapping)
    

    【讨论】:

    • 非常感谢! df.columns = ['Date', 'a', 'b', 'c', 'd', 'e', 'f' 'g', 'h', 'i', 'j'] 工作正常
    • df.rename(columns=mapping, inplace=True) 也可以。
    • 如果我使用 df = df.rename(columns=mapping),我会收到错误:TypeError: rename() got an unexpected keyword argument 'columns' 你可能有解决方案吗?谢谢
    【解决方案2】:

    "inplace=True" 成功了。因为我已经多次尝试解决它......如果不指定“inplace = True”,实际结果是什么?我没有看到任何变化。

    【讨论】:

    猜你喜欢
    • 2017-12-19
    • 2014-11-23
    • 2019-11-01
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 2017-01-26
    • 2018-08-16
    相关资源
    最近更新 更多