如何根据多索引添加熊猫数据框?

时间:2019-08-24 14:39:50

标签: python pandas

我有一个熊猫数据框A,如下所示:

enter image description here

A = pd.DataFrame({'v1' : [1,2,2],
         'v2':[2,3,4],
         'weight':[10,11,12]})
A.set_index(['v1','v2'])

enter image description here

B = pd.DataFrame({'v1' : [2,3,4],
         'v2' : [3,5,6],
         'weight':[20,21,22]})
B.set_index(['v1','v2'])

我要针对它们的多索引添加A和B,以形成以下数据框:

enter image description here

我该如何编码..?

提前谢谢

2 个答案:

答案 0 :(得分:0)

加入AB

A = pd.DataFrame({'v1' : [1,2,2],
         'v2':[2,3,4],
         'weight':[10,11,12]}).set_index(['v1', ' v2'])

B = pd.DataFrame({'v1' : [2,3,4],
         'v2' : [3,5,6],
         'weight':[20,21,22]}).set_index(['v1', 'v2'])

C = A.join(B, how='outer', lsuffix='_A', rsuffix='_B').fillna(0)
C['weight'] = C['weight_A'] + C['weight_B']

结果:

       weight_A  weight_B  weight
v1 v2                            
1  2       10.0       0.0    10.0
2  3       11.0      20.0    31.0
   4       12.0       0.0    12.0
3  5        0.0      21.0    21.0
4  6        0.0      22.0    22.0

根据需要拖放weight_Aweight_B

答案 1 :(得分:0)

请注意,例如A.set_index(['v1','v2'])仅创建一个临时结果, 使用新的MultiIndex,但将索引保留在原始DataFrame中 像以前一样。

所以我假设您执行了A.set_index(['v1','v2'], inplace=True), 对于 B DataFrame也是如此。

要生成您的总和,请运行指令:

pd.concat([A,B]).groupby(level=[0,1]).sum()

编辑

如果两个数据框都具有“正常”索引(就像创建它们一样), 您也可以执行一条指令:

pd.concat([A,B]).groupby(['v1', 'v2']).sum()