1

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 :)

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.