I'm performing a left join via merge between two DataFrames, the left one has a MultiIndex, the right has a single index. How can I retain the MultiIndex after the join?
import pandas as pd
import numpy as np
df1 = pd.DataFrame({
'i1': np.arange(0, 100),
'i2': np.arange(0, 100),
'c': np.random.randint(0 , 10, 100)
}).set_index(['i1', 'i2'])
df2 = pd.DataFrame({
'i1': np.arange(0, 100),
'd': np.random.randint(0 , 10, 100)
}).set_index('i1')
merged = df1.merge(df2, how="left", on="i1")
merged.index # => Int64Index i1 but I want the i1, i2 index to remain
I hoped this might be as simple as reassigning the old index, but it looks like there are no ordering guarantees after a merge.
While I could avoid using indexing all together, I need them. The dataset I'm using is large, and I need the speed up gained when merging with indexes.