将两个具有不同索引的 pandas 数据帧逐个元素相加

2023-12-29

我有两个 pandas 数据帧,例如 df1 和 df2,每个数据帧都有一定的大小,但具有不同的索引,我想逐个元素地总结这两个数据帧。我为您提供一个简单的例子来更好地理解这个问题:

dic1 = {'a': [3, 1, 5, 2], 'b': [3, 1, 6, 3], 'c': [6, 7, 3, 0]}
dic2 = {'c': [7, 3, 5, 9], 'd': [9, 0, 2, 5], 'e': [4, 8, 3, 7]}
df1 = pd.DataFrame(dic1)
df2 = pd.DataFrame(dic2, index = [4, 5, 6, 7])

所以 df1 将是

   a  b  c
0  3  3  6
1  1  1  7
2  5  6  3
3  2  3  0

df2 将是

   c  d  e
4  7  9  4
5  3  0  8
6  5  2  3
7  9  5  7

现在如果输入

df1 + df2

我得到的是

    a   b   c   d   e
 0 NaN NaN NaN NaN NaN
 1 NaN NaN NaN NaN NaN
 2 NaN NaN NaN NaN NaN
 3 NaN NaN NaN NaN NaN
 4 NaN NaN NaN NaN NaN
 5 NaN NaN NaN NaN NaN
 6 NaN NaN NaN NaN NaN
 7 NaN NaN NaN NaN NaN

我怎样才能让 pandas 明白我想逐个元素地总结两个数据框?


UPDATE:更好的解决方案皮尔方 https://stackoverflow.com/questions/38618911/sum-up-two-pandas-dataframes-with-different-indexes-element-by-element/38618948#comment64623588_38618948:

In [39]: df1 + df2.values
Out[39]:
    a   b   c
0  10  12  10
1   4   1  15
2  10   8   6
3  11   8   7

旧答案:

In [37]: df1.values + df2.values
Out[37]:
array([[10, 12, 10],
       [ 4,  1, 15],
       [10,  8,  6],
       [11,  8,  7]], dtype=int64)

In [38]: pd.DataFrame(df1.values + df2.values, columns=df1.columns)
Out[38]:
    a   b   c
0  10  12  10
1   4   1  15
2  10   8   6
3  11   8   7
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将两个具有不同索引的 pandas 数据帧逐个元素相加 的相关文章