Search code examples
pythonpandas

How to add a suffix/prefix to a pandas.DataFrame().index?


I wonder is there a method similar to add_suffix that adds a suffix to the index of a dataframe? My current workaround looks like this.

df = pd.DataFrame({'x': [1, 2, 3]}, index=[1, 2, 3])

df = df.T.add_suffix('_x').T

# or 
df.index = df.index.astype(str)+'_x'

Unfortunately, the axis keyword is not supported by add_suffix.


Solution

  • pandas.DataFrame.rename

    pass a callable that gets applied to each index value

    df.rename('{}_x'.format)
    
         x
    1_x  1
    2_x  2
    3_x  3
    

    set_index

    df.set_index(df.index.astype(str) + '_x')
    
         x
    1_x  1
    2_x  2
    3_x  3