简体   繁体   中英

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 .

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM