6

Considering a simple df:

HeaderA | HeaderB | HeaderC 
    476      4365      457

Is there a way to rename all columns, for example to add to all columns an "X" in the end?

HeaderAX | HeaderBX | HeaderCX 
    476      4365      457

I am concatenating multiple dataframes and want to easily differentiate the columns dependent on which dataset they came from.

Or is this the only way?

df.rename(columns={'HeaderA': 'HeaderAX'}, inplace=True)

I have over 50 column headers and ten files; so the above approach will take a long time.

Thank You

jeangelj
  • 4,338
  • 16
  • 54
  • 98

4 Answers4

12

pd.DataFrame.add_suffix

df.add_suffix('X')

   HeaderAX  HeaderBX  HeaderCX
0       476      4365       457

And the sister method
pd.DataFrame.add_prefix

df.add_prefix('X')

   XHeaderA  XHeaderB  XHeaderC
0       476      4365       457

You can also use the pd.DataFrame.rename method and pass a function. To accomplish the same thing:

df.rename(columns='{}X'.format)

   HeaderAX  HeaderBX  HeaderCX
0       476      4365       457

In this example, '{}X'.format is a function that takes a single argument and appends an 'X'

The advantage of this method is that you can use inplace=True if you chose to.

piRSquared
  • 285,575
  • 57
  • 475
  • 624
2
df.columns = list(map(lambda s: s+'X', df.columns))
ayhan
  • 70,170
  • 20
  • 182
  • 203
JavNoor
  • 402
  • 2
  • 11
2

From SO post. Let's try using a lambda function in rename:

df.rename(columns = lambda x: x+'X', inplace = True)

Community
  • 1
  • 1
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
1
df.columns = [column + 'X' for column in df.columns]
Grr
  • 15,553
  • 7
  • 65
  • 85