【问题标题】:Passing a string variable to rename function pandas传递字符串变量以重命名函数 pandas
【发布时间】:2019-02-17 16:11:07
【问题描述】:

我正在尝试通过将字符串变量传递给重命名函数并得到以下错误来重命名 DataFrame 中的单个列,非常感谢任何帮助。

import pandas as pd

new = "new_name"

df.rename(index=str, columns={"old_name": new})

错误:

TypeError: 'set' object is not callable

【问题讨论】:

    标签: pandas rename


    【解决方案1】:

    您不需要 index=str 位,除非您的列是您的索引,否则这将起作用:

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

    输入:

       ID1  old_name      Date
    0    1    2      1/1/2018
    1    1    2      3/1/2018
    2    1    2      4/5/2018 
    

    输出:

       ID1    new_name      Date
    0    1         2    1/1/2018
    1    1         2    3/1/2018
    2    1         2    4/5/2018       
    

    如果你想保存它:

    df = df.rename(columns={'old_name':new})
    

    如果要重命名索引:

    df.index.rename(new, inplace=True)
    

    输出:

              ID1   ID2      Date
    new_name                    
    0           1    2    1/1/2018
    1           1    2    3/1/2018
    2           1    2    4/5/2018
    

    【讨论】:

      猜你喜欢
      • 2015-08-03
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      • 2016-01-17
      • 2020-10-03
      相关资源
      最近更新 更多