Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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.

like image 988
Soren Avatar asked May 22 '18 17:05

Soren


People also ask

How do you add a suffix in Pandas?

To add a string after each column label of DataFrame in Pandas, call add_suffix() method on this DataFrame, and pass the suffix string as argument to add_suffix() method.

How do you add a prefix to a DataFrame?

The add_prefix() function is used to prefix labels with string prefix. For Series, the row labels are prefixed. For DataFrame, the column labels are prefixed. The string to add before each label.

How do you add a prefix to a specific column in Pandas?

To add a string before each column label of DataFrame in Pandas, call add_prefix() method on this DataFrame, and pass the prefix string as argument to add_prefix() method.


1 Answers

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
like image 198
piRSquared Avatar answered Oct 17 '22 07:10

piRSquared