pandas 使用多索引合并两个数据帧
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46551951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merge two dataframes with multi-index
提问by Andreuccio
I have seen several posts about this but I could not get my head around how merge, join and concat would deal with this. How can I merge two dataframes to find matching indexes?
我看过几篇关于这个的帖子,但我无法理解合并、连接和连接将如何处理这个问题。如何合并两个数据帧以找到匹配的索引?
in:
在:
import pandas as pd
import numpy as np
row_x1 = ['a1','b1','c1']
row_x2 = ['a2','b2','c2']
row_x3 = ['a3','b3','c3']
row_x4 = ['a4','b4','c4']
index_arrays = [np.array(['first', 'first', 'second', 'second']), np.array(['one','two','one','two'])]
df1 = pd.DataFrame([row_x1,row_x2,row_x3,row_x4], columns=list('ABC'), index=index_arrays)
print(df1)
out:
出去:
A B C
first one a1 b1 c1
two a2 b2 c2
second one a3 b3 c3
two a4 b4 c4
in:
在:
row_y1 = ['d1','e1','f1']
row_y2 = ['d2','e2','f2']
df2 = pd.DataFrame([row_y1,row_y2], columns=list('DEF'), index=['first','second'])
print(df2)
out
出去
D E F
first d1 e1 f1
second d2 e2 f2
in other words, how can I merge them to achieve df3 (as follows)?
换句话说,我如何合并它们以实现 df3(如下)?
in
在
row_x1 = ['a1','b1','c1']
row_x2 = ['a2','b2','c2']
row_x3 = ['a3','b3','c3']
row_x4 = ['a4','b4','c4']
row_y1 = ['d1','e1','f1']
row_y2 = ['d2','e2','f2']
row_z1 = row_x1 + row_y1
row_z2 = row_x2 + row_y1
row_z3 = row_x3 + row_y2
row_z4 = row_x4 + row_y2
df3 = pd.DataFrame([row_z1,row_z2,row_z3,row_z4], columns=list('ABCDEF'), index=index_arrays)
print(df3)
out
出去
A B C D E F
first one a1 b1 c1 d1 e1 f1
two a2 b2 c2 d1 e1 f1
second one a3 b3 c3 d2 e2 f2
two a4 b4 c4 d2 e2 f2
回答by piRSquared
Option 1
Use pd.DataFrame.reindex
+ pd.DataFrame.join
reindex
has a convenient level
parameter that allows you to expand on the index levels not present.
选项 1
使用pd.DataFrame.reindex
+pd.DataFrame.join
reindex
有一个方便的level
参数,允许您扩展不存在的索引级别。
df1.join(df2.reindex(df1.index, level=0))
A B C D E F
first one a1 b1 c1 d1 e1 f1
two a2 b2 c2 d1 e1 f1
second one a3 b3 c3 d2 e2 f2
two a4 b4 c4 d2 e2 f2
Option 2
You can rename your axes and join
will work
选项 2
你可以重命名你的轴并且join
会起作用
df1.rename_axis(['a', 'b']).join(df2.rename_axis('a'))
A B C D E F
a b
first one a1 b1 c1 d1 e1 f1
two a2 b2 c2 d1 e1 f1
second one a3 b3 c3 d2 e2 f2
two a4 b4 c4 d2 e2 f2
You can follow that up with another rename_axis
to get desired results
您可以跟进另一个rename_axis
以获得所需的结果
df1.rename_axis(['a', 'b']).join(df2.rename_axis('a')).rename_axis([None, None])
A B C D E F
first one a1 b1 c1 d1 e1 f1
two a2 b2 c2 d1 e1 f1
second one a3 b3 c3 d2 e2 f2
two a4 b4 c4 d2 e2 f2