drango
drango

Reputation: 19

Rename columns by another pandas

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.

Upvotes: 2

Views: 112

Answers (2)

Mayank Porwal
Mayank Porwal

Reputation: 34046

Use map:

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

Upvotes: 2

jezrael
jezrael

Reputation: 862511

Create dictionary by zip and pass to rename:

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

Upvotes: 4

Related Questions