Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add new columns based on a lookup table in pandas

I have two DataFrames:

df1:

block, name
A, X
B, Y
C, X

and df2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type, name, area
G1, X, 0.10
G1, Y, 0.20
G2, X, 0.50
G2, Y, 0.75

The end result I want to achieve is:

block, name, G1_area, G2_area
A, X, 0.1, 0.5
B, Y, 0.2, 0.75
C, X, 0.1, 0.5

I am not sure how to go about doing this lookup and adding these two columns in Pandas. I tried different variations of pd.merge on name without any success. Any ideas?

>Solution :

You could merge + pivot:

out = (df1.merge(df2, on='name')
       .pivot(['block', 'name'], 'type', 'area')
       .add_suffix('_area')
       .reset_index().rename_axis([None], axis=1))

Output:

  block name  G1_area  G2_area
0     A    X      0.1     0.50
1     B    Y      0.2     0.75
2     C    X      0.1     0.50
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading