【发布时间】: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
【问题讨论】:
我正在尝试通过将字符串变量传递给重命名函数并得到以下错误来重命名 DataFrame 中的单个列,非常感谢任何帮助。
import pandas as pd
new = "new_name"
df.rename(index=str, columns={"old_name": new})
错误:
TypeError: 'set' object is not callable
【问题讨论】:
您不需要 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
【讨论】: