Home > Mobile >  How can I replace the column name in a panda dataframe
How can I replace the column name in a panda dataframe

Time:10-05

I have a excel file as

Old_name  new_name
 xyz        abc
 opq        klm

And I have my dataframe as like this

Id   timestamp    xyz  opq
1   04-10-2021    3    4
2   05-10-2021    4    9 

As you see I have my old names as column name and I would like to map and replace them with new name as in my csv file. How can I do that?

CodePudding user response:

Try with rename:

df.rename(columns=col_names.set_index('Old_name')['new_name'], inplace=True)

# verify
print(df)

Output:

   Id   timestamp  abc  klm
0   1  04-10-2021    3    4
1   2  05-10-2021    4    9

CodePudding user response:

We can create a mapping using set_index then perform a noncomprehensive mapping with something like Series.get:

mapper = df1.set_index('Old_name')['new_name']
df2.columns = df2.columns.map(lambda x: mapper.get(x, x))

Or with to_series Series.replace:

mapper = df1.set_index('Old_name')['new_name']
df2.columns = df2.columns.to_series().replace(mapper)

df2:

   Id   timestamp  abc  klm
0   1  04-10-2021    3    4
1   2  05-10-2021    4    9

Setup Used:

import pandas as pd

df1 = pd.DataFrame({'Old_name': ['xyz', 'opq'], 'new_name': ['abc', 'klm']})
df2 = pd.DataFrame({'Id': [1, 2], 'timestamp': ['04-10-2021', '05-10-2021'],
                    'xyz': [3, 4], 'opq': [4, 9]})
  • Related