Reputation: 2273
I am looking forward to rename the indices names 'Juan Gonzalez' to 'Jason', 'Jorge Sanchez' to 'George' and 'Miguel Sanz' to 'Michael'
age height(cm) weight(kg)
People
Juan Gonzalez 22 181 60
Jorge Sanchez 34 190 84
Miguel Sanz 50 166 59
I thought it worked like when renaming columns:
df.rename(columns={,,}, inplace=True)
However when I try
df.rename(index={'Juan Gonzalez':'Jason','Jorge Sanchez':'George','Miguel Sanz':'Michael'}, inplace=True)
It doesn't works, it returns the same dataframe with same indices names
Upvotes: 1
Views: 159
Reputation: 862671
It seems there are some whitespaces in index values.
For remove it use strip
:
df.index = df.index.str.strip()
Or add parameter skipinitialspace=True
to read_csv
.
Samples:
import pandas as pd
from pandas.compat import StringIO
temp=u"""People,age height(cm),weight(kg)
Juan Gonzalez,22,181,60
Jorge Sanchez,34,190,84
Miguel Sanz,50,166,59"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp), skipinitialspace=True)
print (df)
People age height(cm) weight(kg)
Juan Gonzalez 22 181 60
Jorge Sanchez 34 190 84
Miguel Sanz 50 166 59
print (df.index)
Index(['Juan Gonzalez', 'Jorge Sanchez', 'Miguel Sanz'], dtype='object')
d = {'Juan Gonzalez':'Jason','Jorge Sanchez':'George','Miguel Sanz':'Michael'}
df.rename(index=d, inplace=True)
print (df)
People age height(cm) weight(kg)
Jason 22 181 60
George 34 190 84
Michael 50 166 59
import pandas as pd
from pandas.compat import StringIO
temp=u"""People,age height(cm),weight(kg)
Juan Gonzalez,22,181,60
Jorge Sanchez,34,190,84
Miguel Sanz,50,166,59"""
#after testing replace 'StringIO(temp)' to 'filename.csv'
df = pd.read_csv(StringIO(temp))
print (df)
People age height(cm) weight(kg)
Juan Gonzalez 22 181 60
Jorge Sanchez 34 190 84
Miguel Sanz 50 166 59
print (df.index)
Index([' Juan Gonzalez', ' Jorge Sanchez', 'Miguel Sanz'], dtype='object')
df.index = df.index.str.strip()
print (df.index)
Index(['Juan Gonzalez', 'Jorge Sanchez', 'Miguel Sanz'], dtype='object')
d = {'Juan Gonzalez':'Jason','Jorge Sanchez':'George','Miguel Sanz':'Michael'}
df.rename(index=d, inplace=True)
print (df)
People age height(cm) weight(kg)
Jason 22 181 60
George 34 190 84
Michael 50 166 59
Upvotes: 2