I have a dataframe that looks like the following
index | 0 | feature2 | feature3 | |
---|---|---|---|---|
0 | zipcode | 0.10 | y | z |
1 | latitude | 0.56 | y | z |
2 | longitude | 0.39 | y | 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.
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).
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):
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'})
About using df.rename(index=...)
vs. df.rename(columns=...)
those would have different results. Setting the index
parameter would rename the rows, setting the columns
parameter would instead rename the columns.
Eg:
df = df.rename(column={0: 'feature_rank'})
index | feature_rank | feature2 | feature3 | |
---|---|---|---|---|
0 | zipcode | 0.10 | y | z |
1 | latitude | 0.56 | y | z |
2 | longitude | 0.39 | y | z |
Instead:
df = df.rename(index={0: 'feature_rank'})
index | 0 | feature2 | feature3 | |
---|---|---|---|---|
feature_rank | zipcode | 0.10 | y | z |
1 | latitude | 0.56 | y | z |
2 | longitude | 0.39 | y | z |
Hope this will work.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.