0

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

tedioustortoise
  • 259
  • 3
  • 20

1 Answers1

1

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
Patrick
  • 1,189
  • 5
  • 11
  • 19