Reputation: 61
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
Upvotes: 2
Views: 6011
Reputation: 4142
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(columns={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(columns={0: 'feature_rank'}, inplace=True)
If you want to rename multiple columns you can just add them to the dictionary, e.g.:
df = df.rename(columns={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.
E.g.:
df = df.rename(columns={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 |
Upvotes: 5
Reputation: 672
You should try this:
df.rename(columns={'0':'feature_rank', 'feature2': 'my_new_name_for_feature2'}, inplace=True)
Upvotes: 1
Reputation: 21
Hope this will work.
df.rename(columns={'0': 'feature_rank'}, inplace=True)
Upvotes: 2