逐个元素地汇总两个具有不同索引的 pandas 数据帧 [英] sum up two pandas dataframes with different indexes element by element
本文介绍了逐个元素地汇总两个具有不同索引的 pandas 数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个大熊猫数据帧,分别为df1和df2,大小各异,但索引不同,我想逐个元素地总结两个数据帧。我提供了一个简单的例子来更好地理解问题:
I have two pandas dataframes, say df1 and df2, of some size each but with different indexes and I would like to sum up the two dataframes element by element. I provide you an easy example to better understand the problem:
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
我如何让熊猫理解我想对两个数据框进行汇总
How can I make pandas understand that I want to sum up the two dataframe just element by element?
推荐答案
更新:来自piRSquared :
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
这篇关于逐个元素地汇总两个具有不同索引的 pandas 数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文