0

I have a dataframe df1 like the following:

ID          Name      Test1    
100         Ben       30 
111         Mark      40 
122         Dave      25

and another dataframe df2 like the following:

ID          Test2     Test3
100         22        29
109         44        31
122         37        34

and I am trying to obtain df1 like the following:

ID          Name      Test1     Test2     Test3
100         Ben       30        22        29
111         Mark      40        None      None
122         Dave      25        37        34

I tried using isin to find the index that matched with the IDs of both dataframes but it gave me errors since the sizes of dataframes are different.

idx = df1.index[df1['ID'].isin(df2['ID'])==True]
df1['Test2'] = df2['Test2'].iloc[idx]
df1['Test3'] = df2['Test3'].iloc[idx]

IndexError: positional indexers are out-of-bounds

Is there a way to copy the columns where the ID matches and put None values where it does not?

1 Answers1

1

You want pandas.merge:

>>> pd.merge(df1, df2, on="ID", how="left")
    ID  Name  Test1  Test2  Test3
0  100   Ben     30   22.0   29.0
1  111  Mark     40    NaN    NaN
2  122  Dave     25   37.0   34.0
not_speshal
  • 22,093
  • 2
  • 15
  • 30