naura tsalits
naura tsalits

Reputation: 19

How to rename the column names with another dataframe rows?

I have a dataframe with column names: df1

A_01 A_02 B_03 C_04
 0    0    0    1
 1    2    1    0
 0    1    0    3

also, df2:

no. value
01  1103
02  1105
03  1210
04  1306

How to rename df1 columns with the value on df2 like as:

1103 1105 1210 1306
 0    0    0    1
 1    2    1    0
 0    1    0    3

Upvotes: 2

Views: 622

Answers (1)

harpan
harpan

Reputation: 8631

You need:

df1.columns = df1.columns.str.split('_').str[1].map(df2.set_index('no.')['value'])

Output:

    1103    1105    1210    1306
0   0         0      0         1
1   1         2      1         0
2   0         1      0         3

Upvotes: 2

Related Questions