Python pandas rename multiple column headers in the same way

Given a simple df:

HeaderA | HeaderB | HeaderC 
    476      4365      457

Is there a way to rename all columns, for example, to add “X” at the end to all columns?

HeaderAX | HeaderBX | HeaderCX 
    476      4365      457

I am combining several data frames and want to easily distinguish between columns depending on the data set from which they were derived.

Or is this the only way?

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

I have over 50 column headers and ten files; therefore, the above approach will take a lot of time.

thank

+4
source share
4 answers

pd.DataFrame.add_suffix

df.add_suffix('X')

   HeaderAX  HeaderBX  HeaderCX
0       476      4365       457

And sister method
pd.DataFrame.add_prefix

df.add_prefix('X')

   XHeaderA  XHeaderB  XHeaderC
0       476      4365       457

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

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

   HeaderAX  HeaderBX  HeaderCX
0       476      4365       457

'{}X'.format - , 'X'

, inplace=True, .

+8

SO post. lambda- :

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

+2
df.columns = [column + 'X' for column in df.columns]
+1
source
df.columns = list(map(lambda s: s+'X', df.columns))
+1
source

Source: https://habr.com/ru/post/1674998/


All Articles