我想问一个关于在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()才能使此工作?
谢谢
好像你需要用它们的组合。
输出:
除了使用@ALollz所指的索引名之外,您只需使用
loc
,它将自动匹配索引一般公式是
rename_axis
您可以重命名一个的索引级别并让
join
执行它的操作concat
相关问题 更多 >
编程相关推荐