Home > front end >  Rename columns by another pandas
Rename columns by another pandas

Time:12-04

I want to rename column name using another dataframe.

df_A is

#                a   b   x 
# date
# 2017-11-01     65  12  1
# 2017-11-02     26  1   5
# 2017-11-03     47  5   6

df_B is

# keys  names
#    a    X   
#    b    Y  
#    x    Z  

From these, I want to get df_c. df_c

#                X   Y   Z 
# date
# 2017-11-01     65  12  1
# 2017-11-02     26  1   5
# 2017-11-03     47  5   6

I think it is easy to do, and may be use dict, but i donno what to do. Please help me.

CodePudding user response:

Create dictionary by zip and pass to rename:

df_A = df_A.rename(columns=dict(zip(df_B['keys'], df_B['names'])))

CodePudding user response:

Use map:

In [1196]: d = df_B.set_index('keys')['names'].to_dict()
In [1203]: df_A.columns = df_A.columns.map(d)
  • Related