How to keep index when using pandas merge
Solution 1:
In [5]: a.reset_index().merge(b, how="left").set_index('index')
Out[5]:
col1 to_merge_on col2
index
a 1 1 1
b 2 3 2
c 3 4 NaN
Note that for some left merge operations, you may end up with more rows than in a
when there are multiple matches between a
and b
. In this case, you may need to drop duplicates.
Solution 2:
You can make a copy of index on left dataframe and do merge.
a['copy_index'] = a.index
a.merge(b, how='left')
I found this simple method very useful while working with large dataframe and using pd.merge_asof()
(or dd.merge_asof()
).
This approach would be superior when resetting index is expensive (large dataframe).
Solution 3:
There is a non-pd.merge solution using Series.map
and DataFrame.set_index
.
In: a['col2'] = a['to_merge_on'].map(b.set_index('to_merge_on')['col2']))
In: a['col2']
Out:
col1 to_merge_on col2
a 1 1 1.0
b 2 3 2.0
c 3 4 NaN
This doesn't introduce a dummy index
name for the index.
Note however that there is no DataFrame.map
method, and so this approach is not for multiple columns.
Solution 4:
df1 = df1.merge(df2, how="inner", left_index=True, right_index=True)
This allows to preserve the index of df1
Solution 5:
Assuming that the resulting df has the same number of rows and order as your first df, you can do this:
c = pd.merge(a, b, on='to_merge_on')
c.set_index(a.index,inplace=True)