How to use DataFrame.rename to rename a dataframe index (not inplace)

3.7k views Asked by At

I'm highly confused by the DataFrame.rename docs.

They suggest I should be able to rename indexes the same way as columns. It ain't so:

import pandas as pd
df = pd.DataFrame([1], columns=["A"])
df.index.name = 'i'

print df
print df.rename(columns={"A":"B"})  # Success! A is renamed B
print df.rename(index={"i":"j"})    # No-op
print df.rename({"i":"j"}, axis=0)    # No-op
print df.rename({"i":"j"}, axis=1)    # No-op

print df.rename(index={"i":"j"}, axis=1) #  Cannot specify both 'axis' and any of 'index' or 'columns'.
print df.rename(index={"i":"j"}, axis="index")  #  Cannot specify both 'axis' and any of 'index' or 'columns'.
print df.rename(index={"i":"j"}, axis="columns") #  Cannot specify both 'axis' and any of 'index' or 'columns'.
print df.rename(index={"i":"j"}, axis=0) #  Cannot specify both 'axis' and any of 'index' or 'columns'.
1

There are 1 answers

5
BENY On BEST ANSWER

rename + index will change the index not the index name

df.rename(index={0:'j'})
Out[310]: 
   A
i   
j  1

rename_axis will change the index name

df.rename_axis('j',axis=0)
Out[315]: 
   A
j   
0  1

Since rename_axis is going to deprecated

df.index.rename('j',inplace=True)
df
Out[328]: 
   A
j   
0  1