Suman Chowdhury
Suman Chowdhury

Reputation: 53

Updating dataframe column names based on values given in another dataframe

I am very new to python. I am trying to rename the columns of a data frame based on another dataframe.

Essentially My data looks like

DataFrame1

A    B    C   D
1    2    3   4

I have another table that looks like this' DataFrame2

Col1    Col2
A       E
B       Q
C       R
D       Z

I want to rename the columns of my first data frame based on this table so that it will come out: Note. The columns name order are not same.

E    Q    R    Z
1    2    3    4

Upvotes: 1

Views: 2341

Answers (2)

Bharath M Shetty
Bharath M Shetty

Reputation: 30605

Use map with get by setting index i.e

df.columns = df.columns.map(df2.set_index('Col1')['Col2'].get)

   E  Q  R  Z
0  1  2  3  4

Upvotes: 4

jezrael
jezrael

Reputation: 862511

Use rename by dictionary created by zip:

d = dict(zip(df1['Col1'], df1['Col2']))
df = df.rename(columns=d)
print (df)
   E  Q  R  Z
0  1  2  3  4

Upvotes: 5

Related Questions