简体   繁体   English

将 dataframe 的列从 0 重命名为字符串(重命名无效)

[英]Rename column of dataframe from 0 to a string (rename not working)

I have a dataframe that looks like the following我有一个 dataframe,如下所示

index指数 0 0 feature2特征2 feature3特点3
0 0 zipcode邮政编码 0.10 0.10 y z z
1 1个 latitude纬度 0.56 0.56 y z z
2 2个 longitude经度 0.39 0.39 y z z

I have used the following code to change the 0, the third column name to something else, but when I output the dataframe again nothing has changed and the column is still 0.我使用以下代码将第三列名称 0 更改为其他名称,但是当我再次输入 output 和 dataframe 时,什么都没有改变,该列仍然是 0。

df.rename(index = {0: 'feature_rank'})
# Or alternatively
df.rename(column = {0: 'feature_rank'})

I would also like to know if it is possible to change the name of the second column to something else.我还想知道是否可以将第二列的名称更改为其他名称。 Once again rename is not working for the 'index' column重命名再次不适用于“索引”列

DataFrame.rename() returns you a new dataframe with the columns renamed (this is usefull when doing method-chaining). DataFrame.rename()返回一个新的 dataframe,其中的列已重命名(这在进行方法链接时很有用)。

You want to keep the result by doing:你想通过这样做来保持结果:

df = df.rename(column={0: 'feature_rank'})

Alternatively it has an argument (called inplace ) that allows you to do the operation in place (so you wouldn't need to re-assign):或者,它有一个参数(称为inplace ),允许您就地执行操作(因此您不需要重新分配):

df.rename(column={0: 'feature_rank'}, inplace=True)

If you want to rename multiple columns you can just add them to the dictionary, eg:如果你想重命名多列,你可以将它们添加到字典中,例如:

df = df.rename(column={0: 'feature_rank', 'feature2': 'my_new_name_for_feature2'})

Note笔记

About using df.rename(index=...) vs. df.rename(columns=...) those would have different results.关于使用df.rename(index=...)df.rename(columns=...)那些会有不同的结果。 Setting the index parameter would rename the rows, setting the columns parameter would instead rename the columns.设置index参数会重命名行,设置columns参数则会重命名列。

Eg:例如:

df = df.rename(column={0: 'feature_rank'})
index指数 feature_rank feature_rank feature2特征2 feature3特点3
0 0 zipcode邮政编码 0.10 0.10 y z z
1 1个 latitude纬度 0.56 0.56 y z z
2 2个 longitude经度 0.39 0.39 y z z

Instead:反而:

df = df.rename(index={0: 'feature_rank'})
index指数 0 0 feature2特征2 feature3特点3
feature_rank feature_rank zipcode邮政编码 0.10 0.10 y z z
1 1个 latitude纬度 0.56 0.56 y z z
2 2个 longitude经度 0.39 0.39 y z z

Hope this will work.希望这会奏效。

df.rename(columns = {'0':'feature_rank'}, inplace = True) df.rename(columns = {'0':'feature_rank'}, inplace = True)

You should try this:你应该试试这个:

df.rename(column={'0':'feature_rank', 'feature2': 'my_new_name_for_feature2'}, inplace=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM