actnmk
actnmk

Reputation: 166

how to map value from another dataframe to header of another dataframe

I have 2 dataframes:

df1 = pd.DataFrame({'A':[1,2,3,4],
                    'B':[5,6,7,8],
                    'D':[9,10,11,12]})

and

df2 = pd.DataFrame({'type':['A', 'B', 'C', 'D', 'E'],
                    'color':['yellow', 'green', 'red', 'pink', 'black'],
                    'size':['S', 'M', 'L', 'S', 'M']})

I want to map Information from df2 to Header of df1, the result should look like below:

enter image description here

how can I do this? Many thanks :)

Upvotes: 1

Views: 350

Answers (1)

jezrael
jezrael

Reputation: 863611

Use rename with aggregate values by DataFrame.agg:

df1 = pd.DataFrame({'A1':[1,2,3,4],
                    'B':[5,6,7,8],
                    'D':[9,10,11,12]})


s = df2.set_index('type', drop=False).agg(','.join, axis=1)
df1 = df1.rename(columns=s)
print (df1)
   A1  B,green,M  D,pink,S
0   1          5         9
1   2          6        10
2   3          7        11
3   4          8        12

For () need more processing:

s = df2.set_index('type').agg(','.join, axis=1).add(')').radd('(')
s = s.index +' ' + s
df1 = df1.rename(columns=s)
print (df1)
   A (yellow,S)  B (green,M)  D (pink,S)
0             1            5           9
1             2            6          10
2             3            7          11
3             4            8          12

Upvotes: 4

Related Questions