Reputation: 3841
I want to merge two DataFrames based on their common index. All new index entries from DataFrame B should be added to the result. If both dataframes have an entry for the same index, then the result should only contain the value from DataFrame B.
DataFrame A DataFrame B
----------- ------------
Index col1 Index col1
1 1A 1 1B
2 2A 3 3B
Result
------------
Index col1
1 1B # Overridden from DataFrame B
2 2A # From DataSet A
3 3B # Added from B since it not exists in A
I've tried already the following. But it results in two columns and I want just a single column in my result:
df1 = pd.DataFrame(index= [1, 2],
data = ['1A', '2A'],
columns=['col1'])
df2 = pd.DataFrame(index= [1, 3],
data=['1B', '3B'],
columns=['col1'])
df3 = pd.merge(df1, df2, how='outer', left_index=True, right_index=True)
Upvotes: 1
Views: 234
Reputation: 323386
By using update
+ combine_first
df1.update(df2)
df1
Out[525]:
col1
Index
1 1B
2 2A
df1.combine_first(df2)
Out[526]:
col1
Index
1 1B
2 2A
3 3B
Upvotes: 1