Reputation: 717
I have a dataframe that looks like this:
RIC | base
AAPL| AA
IBM |
AMD |
and another table with same fields but different values:
RIC | base
AAPL | AA
IBM |
AMD | AM
I would like to join the two tables to get this resultant table:
RIC | base
AAPL | AA
IBM |
AMD | AM
How can I do that?
Upvotes: 1
Views: 47
Reputation: 294218
Do you notice that your desired result is the same as your second dataframe?
I think you meant something like this:
Consider the two dataframes d1
and d2
d1 = pd.DataFrame(dict(RIC=['AAPL', 'IBM', 'AMD'], base=['AA', None, None]))
d2 = pd.DataFrame(dict(RIC=['AAPL', 'IBM', 'AMD'], base=['aa', 'IB', 'AM']))
print(d1)
print()
print(d2)
RIC base
0 AAPL AA
1 IBM None
2 AMD None
RIC base
0 AAPL aa
1 IBM IB
2 AMD AM
We'll use set_index
and combine_first
d1.set_index('RIC').combine_first(d2.set_index('RIC')).reset_index()
RIC base
0 AAPL AA
1 IBM IB
2 AMD AM
This approach takes the values from the first dataframe when it exists. Otherwise, it takes the value from the second dataframe.
Upvotes: 2