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

Pandas create new column referencing another column in another data frame

I am attempting to add another column to df2 referencing df1

>>> df1
    col1  col2
0     A   Name A
1     B   Name B


>>> df2
    col1  col2
0     A   12.3
1     B   34.0
2     A   103.2

so that col1 in df2 is used to get the col2 value from df1, i.e. to produce:

>>> df2
    col1  col2   col3 
0     A   12.3   Name A
1     B   34.0   Name B
2     A   103.2  Name A

(I can do it with creating an empty column in df2 and then iterating over rows such as for n in range(0,df.shape[0])…then iloc, but apparently this is bad practice.)

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

>Solution :

You can join the two dataframes

df2 = df2.merge(df1, how='left', on='col1')

Input:

df1
  col1   col2
0    A  NameA
1    B  NameB

df2
  col1   col3
0    A   12.3
1    B   34.0
2    A  103.2

Output:

  col1   col3   col2
0    A   12.3  NameA
1    B   34.0  NameB
2    A  103.2  NameA
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