Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将数据帧求和到多索引_Python_Pandas_Dataframe - Fatal编程技术网

Python 将数据帧求和到多索引

Python 将数据帧求和到多索引,python,pandas,dataframe,Python,Pandas,Dataframe,我有两个具有不同索引的数据帧,如: import pandas as pd a = pd.DataFrame([1, 2, 3], index=['a', 'b', 'c'], columns=['one']) b = pd.DataFrame([5, 6], index=['d', 'e'], columns=['two']) 我可以使用以下方法创建“笛卡尔”多索引: a_plus_b = pd.MultiIndex.from_product([a.index,b.index]) 这将变成

我有两个具有不同索引的数据帧,如:

import pandas as pd
a = pd.DataFrame([1, 2, 3], index=['a', 'b', 'c'],
columns=['one'])
b = pd.DataFrame([5, 6], index=['d', 'e'],
columns=['two'])
我可以使用以下方法创建“笛卡尔”多索引:

a_plus_b = pd.MultiIndex.from_product([a.index,b.index])
这将变成一个空的多重索引:

MultiIndex(levels=[['a', 'b', 'c'], ['d', 'e']],
       labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]])
如何创建笛卡尔和,如下所示

'a' 'd' 6 # 1 + 5
    'e' 7 # 1 + 6
'b' 'd' 7 # 2 + 5
    'e' 8 # 2 + 6
'c' 'd' 8 # 3 + 5
    'e' 9 # 3 + 6
第一级和第二级使用:

s = a['one'].reindex(a_plus_b, level=0) + b['two'].reindex(a_plus_b, level=1)
print (s)
a  d    6
   e    7
b  d    7
   e    8
c  d    8
   e    9
dtype: int64

通过使用
pd.merge
,可以避免显式创建
多索引的中间步骤:

res = pd.merge(a.rename_axis('A').reset_index().assign(key=1),
               b.rename_axis('B').reset_index().assign(key=1), on='key')

res = res.assign(total=res['one'] + res['two'])\
         .groupby(['A', 'B'])['total'].sum()

print(res)

A  B
a  d    6
   e    7
b  d    7
   e    8
c  d    8
   e    9
Name: total, dtype: int64