将多个数据帧组合成一个数据帧,根据索引将它们的值相加

Ale*_*lex 3 python sum pandas

我有几个 pandas 数据帧,每个数据帧中都有一列整数,我想创建一个新的数据帧,其中每个索引处的值之和。它们的索引将有一些重叠的条目,这些是我想要将其值加在一起的不定值。如果仅在一个数据帧中找到索引,我希望新的数据帧(或系列)包含该索引并仅使用该一个值作为其值。这看起来很简单,但我无法弄清楚,并且文档似乎更多地关注于连接数据帧而不是组合它们的值。基本上,给定两个数据框,如下所示:

>>> df1
   0
a  3
b  7
d  2
>>> df2
    0
c  11
d  19
Run Code Online (Sandbox Code Playgroud)

我希望最终的输出如下所示:

>>> df3
    0
a   3
b   7
c  11
d  21
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Kim*_*rly 5

最简单的答案,如果您只添加两个数据框:

# fill_value parameter specifies how to treat missing rows, since you can't add NaN (i.e. add 0)
df3 = df1.add(df2, fill_value=0)

df3
Out[18]: 
   0
a  3
b  7
c  13
d  19
Run Code Online (Sandbox Code Playgroud)

但是,如果您想添加两个以上,最简单、最快的方法更像是这样:

import pandas as pd

# initialize example inputs
df1 = pd.DataFrame([3, 7, 2], index=['a', 'b', 'c'])
df2 = pd.DataFrame([11, 19], index=['c', 'd'])
df3 = pd.DataFrame([3, 7, 11, 21], index=['a', 'b', 'c', 'd'])

# when concatenating with axis=1, columns are added side by side. Rows are matched with other rows having the same index.
aggregate_df = pd.concat([df1, df2, df3], axis=1)

# sum across columns (axis=1).  Convert resulting Series to DataFrame
df4 = aggregate_df.sum(axis=1).to_frame()

df4
Out[11]: 
    0
a   6
b  14
c  24
d  40
dtype: float64
Run Code Online (Sandbox Code Playgroud)