我想询问有关在Pandas中合并多级索引数据框的问题,以下是一个假设的场景:
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index1 = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
index2 = pd.MultiIndex.from_tuples(tuples, names=['third', 'fourth'])
s1 = pd.DataFrame(np.random.randn(8), index=index1, columns=['s1'])
s2 = pd.DataFrame(np.random.randn(8), index=index2, columns=['s2'])
然后,任选其一
s1.merge(s2, how='left', left_index=True, right_index=True)
或者s1.merge(s2, how='left', left_on=['first', 'second'], right_on=['third', 'fourth'])
会导致错误。
我需要在s1
/s2
中执行reset_index()
吗,才能使这个工作?