考慮以下兩個DataFrames:合併MultIndex DataFrames
arrays1 = [['foo', 'bar', 'bar', 'bar'],
['A', 'D', 'E', 'F']]
tuples1 = list(zip(*arrays1))
columnValues1 = pd.MultiIndex.from_tuples(tuples1)
df1 = pd.DataFrame(np.random.rand(4,4), columns = columnValues1)
print(df1)
foo bar
A D E F
0 0.833444 0.354676 0.468294 0.173005
1 0.409730 0.275342 0.595433 0.322785
2 0.515161 0.340063 0.117509 0.491957
3 0.285594 0.970524 0.322902 0.628351
arrays2 = [['foo', 'foo', 'bar', 'bar'],
['B', 'C', 'G', 'H']]
tuples2 = list(zip(*arrays2))
columnValues2 = pd.MultiIndex.from_tuples(tuples2)
df2 = pd.DataFrame(np.random.rand(4,4), columns = columnValues2)
print(df2)
foo bar
B C G H
0 0.208822 0.762884 0.424412 0.583324
1 0.767560 0.884583 0.716843 0.329719
2 0.147991 0.424748 0.560599 0.828155
3 0.376050 0.436354 0.704379 0.406324
說我想合併這些得到這個:
foo bar
A B C D E F G H
0 0.833444 0.208822 0.762884 0.354676 0.468294 0.173005 0.424412 0.583324
1 0.409730 0.767560 0.884583 0.275342 0.595433 0.322785 0.716843 0.329719
2 0.515161 0.147991 0.424748 0.340063 0.117509 0.491957 0.560599 0.828155
3 0.285594 0.376050 0.436354 0.970524 0.322902 0.628351 0.704379 0.406324
我試圖通過合併:
pd.merge(df1.reset_index(), df2.reset_index(), on=df1.columns.levels[0],
how='inner').set_index(df1.columns.levels[0])
不幸的是我收到以下錯誤信息:
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()
如何合併2個MultiIndex DataFrame? `
實際上,0級除了'foo'和'bar'之外還有更多的標籤。有什麼辦法可以傳遞df1的列順序嗎? – BdB
@BdB,當然,請參閱我的回答中的「更新」 – MaxU
太棒了,感謝您的更新! – BdB