Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check values in dataframe against another dataframe and append values if present

Tags:

python

pandas

I have two dataframes as follows:

DF1
A   B   C
1   2   3
4   5   6
7   8   9

DF2
Match   Values
1       a,d
7       b,c

I want to match DF1['A'] with DF2['Match'] and append DF2['Values'] to DF1 if the value exists

So my result will be:
A    B    C    Values
1    2    3    a,d
7    8    9    b,c

Now I can use the following code to match the values but it's returning an empty dataframe.

df1 = df1[df1['A'].isin(df2['Match'])]

Any help would be appreciated.

like image 773
coding_monkey Avatar asked Oct 17 '22 12:10

coding_monkey


1 Answers

Instead of doing a lookup, you can do this in one step by merging the dataframes:

pd.merge(df1, df2, how='inner', left_on='A', right_on='Match')

Specify how='inner' if you only want records that appear in both, how='left' if you want all of df1's data.

If you want to keep only the Values column:

pd.merge(df1, df2.set_index('Match')['Values'].to_frame(), how='inner', left_on='A', right_index=True)

like image 153
Andrew L Avatar answered Oct 20 '22 10:10

Andrew L