Roo
Roo

Reputation: 912

merge two dataframes using two keys with or operator

I have two dataframes on financial data. Each has two keys, ticker and cusip. I wanted to merge these two datafames based on matching of any of those two keys (not necessary their interaction). If I used

`pd.merge(a , b, how='left' ,  on=['ticker', 'cusip'])

it would return just those observations with matched ticker and cusip. I need to have or operator. something like this in sql is qhat I am asking:

select * from a left join b on a.ticker = b.ticker or a.cusip=b.cusip

I would appreciate your hints.

Upvotes: 0

Views: 42

Answers (1)

Scott Boston
Scott Boston

Reputation: 153510

Do separate merges on each column, and combine the results using pd.concat:

df1 = pd.merge(a, b, how='left', on='ticker')
df2 = pd.merge(a, b, how='left', on='cusip')

df_out = pd.concat([df1, df2])

Upvotes: 1

Related Questions