在 Pandas 中使用列表替换列名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44296648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:42:36  来源:igfitidea点击:

Using lists in Pandas to replace column names

pythonpandas

提问by Shawn

I'm trying to understand my mistake when using df.rename in pandas. Specifically, using the rename function with a tuple executes without error, but no changes are made to the column names.

在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

回答by sparc_spread

You are correct in wanting to pass in a dictwith three entries, one for each column you are renaming, but the dictyou are passing is not. It's a dictof one entry, with one tuple as a key and one as a value.

您想要传入dict包含三个条目的a 是正确的,您要重命名的每一列对应一个条目,但dict您传递的不是。它dict是一个条目,一个元组作为键,一个作为值。

Use a dictcomprehension to turn the tuples into a dict, like this:

使用dict推导式将元组转换为dict,如下所示:

{i:j for i,j in zip(old_colnames,new_colnames)}

So in the context of your code, that's:

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

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

Or just:

要不就:

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

Here's a nice little write-upon comprehensions in general, including the dictcomprehension. It also includes usage of zip.

这是一篇关于一般理解的不错的小文章,包括dict理解。它还包括使用zip.

回答by xmduhan

columns parameter should be this way:

列参数应该是这样的:

{'one': 'pig', 'three': 'seven', 'two': 'cups'}

use this code to get it:

使用此代码获取它:

dict(zip(old_colnames, new_colnames))

If you want to change name of columns, use this code will be more easy:

如果要更改列名,使用此代码会更容易:

f_GreaterArea.columns = ('pig', 'cups', 'seven')