Soerendip
Soerendip

Reputation: 9175

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.

Upvotes: 17

Views: 8991

Answers (2)

ouroboros1
ouroboros1

Reputation: 14369

As of pandas 2.0.0, df.add_prefix and df.add_suffix work on the index with axis=0:

df.add_suffix('_x', axis=0)

     x
1_x  1
2_x  2
3_x  3

Similarly:

df.add_prefix('x_', axis=0)

     x
x_1  1
x_2  2
x_3  3

Default axis=None continues to add prefix/suffix to the column labels, as before. E.g.:

df.add_prefix('x_')

   x_x
1    1
2    2
3    3

Upvotes: 1

piRSquared
piRSquared

Reputation: 294508

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

Upvotes: 25

Related Questions