【问题标题】:Can't Rename Columns of Dataframe [duplicate]无法重命名数据框的列[重复]
【发布时间】:2020-04-28 10:36:18
【问题描述】:

我似乎无法重命名数据框中的列。

我试过这个:df2.columns['Rating','Spread','Cnt']

当我查看数据框时,Cnt 不存在。

我也试过这个:df2.rename(columns={'Rating','Spread','Cnt'}, inplace=True)

同样,在我运行脚本后,Cnt 没有出现。我只有前两个字段名;第三个不断下降。我该如何解决这个问题?

【问题讨论】:

标签: python python-3.x dataframe


【解决方案1】:

你必须告诉 pandas 你想把名字改成什么。

df = df.rename(columns={'some_column': 'new_column'}, axis=1)

【讨论】:

  • 仅供参考,axis=1 在这种情况下是多余的,因为您已将 columns 作为参数传递
  • 我搞定了。谢谢大家。
【解决方案2】:

试试这个

df2.rename(columns={'OldName1':'Rating','OldName2':'Spread','OldName3':'Cnt'}, inplace=True)

也看看这个

Pandas documentation

【讨论】:

    【解决方案3】:

    您需要将字典传递给重命名函数中的列参数,如下所示:

    df.rename(columns={"old_name": "new_name"})
    

    Check the documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 2017-12-19
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      相关资源
      最近更新 更多