使用Pandas中的列表替换列名称

Sha*_*awn 4 python pandas

在熊猫中使用df.rename时,我试图理解我的错误.具体来说,使用带有元组的重命名函数可以无错误地执行,但不会对列名进行任何更改.

f_GreaterArea = pd.DataFrame(np.random.randn(5, 3), 
                index=['a', 'c', 'e', 'f', 'h'],
                columns=['one', 'two', 'three'])

print(f_GreaterArea)

    one       two     three
a  0.278969 -0.676388 -2.464444
c -0.992077 -0.435534  2.267315
e  2.094669 -1.401885  1.243658
f  0.886835  0.195726 -0.132382
h -0.920486 -0.298380  2.227378

old_colnames = ('one', 'two', 'three')
new_colnames = ('pig', 'cups', 'seven')


f_GreaterArea.rename(columns={old_colnames:new_colnames}, inplace=True)

print(f_GreaterArea)

    one       two     three
a  0.278969 -0.676388 -2.464444
c -0.992077 -0.435534  2.267315
e  2.094669 -1.401885  1.243658
f  0.886835  0.195726 -0.132382
h -0.920486 -0.298380  2.227378
Run Code Online (Sandbox Code Playgroud)

spa*_*ead 9

你想要传入dict三个条目是正确的,每个条目对于你要重命名的每个列,但是dict你传递的不是.它dict是一个条目,一个元组作为键,一个作为值.

使用dict理解将元组转换为a dict,如下所示:

{i:j for i,j in zip(old_colnames,new_colnames)}
Run Code Online (Sandbox Code Playgroud)

所以在你的代码的上下文中,那是:

col_rename_dict = {i:j for i,j in zip(old_colnames,new_colnames)}
f_GreaterArea.rename(columns=col_rename_dict, inplace=True)
Run Code Online (Sandbox Code Playgroud)

要不就:

f_GreaterArea.rename(
    columns={i:j for i,j in zip(old_colnames,new_colnames)}, inplace=True
)
Run Code Online (Sandbox Code Playgroud)

这是关于一般理解的一个很好的小写,包括dict理解.它还包括使用zip.


mik*_*key 5

在 python 3.8 及更高版本中,您可以简单地将列名称指定为列表

f_GreaterArea.columns = ['pig', 'cups', 'seven']
Run Code Online (Sandbox Code Playgroud)

我知道这个问题要求一个元组,但从评论来看,OP 似乎试图使用一个列表。