[英]How can I change column names without referencing old column names and without creating a new data frame?
I know I can change column names by doing:我知道我可以通过执行以下操作来更改列名:
df = df.rename(columns = {old_name: new_name})
But I have to rename a lot and the old names are long so I wanna just pass in a list for the new names.但是我必须重命名很多,并且旧名称很长,所以我只想传递新名称的列表。 If I make the new columns its own data frame this works fine:如果我使新列成为自己的数据框,这可以正常工作:
ranks = sw[sw.columns[9:15]]
ranks.columns = ['ranking_1', 'ranking_2', 'ranking_3', 'ranking_4', 'ranking_5', 'ranking_6']
However if I try to just do it with the slice of columns without changing it to its own df, nothing happens:但是,如果我尝试仅使用列切片而不将其更改为自己的 df,则不会发生任何事情:
sw[sw.columns[9:15]].columns = ['ranking_1', 'ranking_2', 'ranking_3', 'ranking_4', 'ranking_5', 'ranking_6']
How can I rename the columns and keep them in the original data frame?如何重命名列并将它们保留在原始数据框中?
This:这个:
sw[sw.columns[9:15]] = ['ranking_1', 'ranking_2', 'ranking_3', 'ranking_4', 'ranking_5', 'ranking_6']
changes the data of your sw
, not the column names.更改sw
的数据,而不是列名。 A manual way to change the column names can be:手动更改列名的方法可以是:
# new column names
new_cols = ['ranking_1', 'ranking_2', 'ranking_3', 'ranking_4', 'ranking_5', 'ranking_6']
# slice the columns name, replace the part you want and concatenate
sw.columns = list(sw.columns[:9]) + new_cols + list(sw.columns[15:])
Or you can also build the dictionary and use rename
:或者您也可以构建字典并使用rename
:
rename_dict = {a:b for a,b in zip(new_cols, sw.columns[9:15])}
sw.rename(columns=rename_dict)
Do you mean something like this?你的意思是这样的吗?
import pandas as pd
df = pd.DataFrame(columns=['A','B','C','D','E',
'F','G','H','I','J',
'K','L','M','N','O'])
col = list(df.columns) # get them all
rankcol = ['ranking_1', 'ranking_2', 'ranking_3',
'ranking_4', 'ranking_5', 'ranking_6']
df.columns = col[:9]+rankcol
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.