[英]How can I add two pandas.DataFrames cellwise?
I have a bunch of pandas.DataFrame
s which are each a table of counts .我有一堆
pandas.DataFrame
,每个都是一个计数表。 I'd like to sum them up to return the totals.我想把它们加起来返回总数。 Ie cellwise, as if I was summing two dimensional histograms or two dimensional arrays.
即 cellwise,就好像我在对二维直方图或二维数组求和。 The output should be a table of the same dimensions as input, but with numerical values summed up.
输出应该是一个与输入具有相同维度的表格,但数值相加。
To make matters worse, the order of the columns may not be preserved.更糟糕的是,列的顺序可能无法保留。
There must be a cool way to do this without looping, but I can't figure it out.必须有一种很酷的方法可以在不循环的情况下执行此操作,但我无法弄清楚。
Here's an example:这是一个例子:
import pandas
df1 = pandas.DataFrame({'A': [3, 1, 2], 'B': [1, 1, 0]})
df2 = pandas.DataFrame({'B': [2, 0, 1], 'A': [4, 1, 6]})
I'm looking for a function something like:我正在寻找类似的功能:
df_cellwise_sum = cellwise_sum(df1, df2)
print(df_cellwise_sum)
which makes:这使得:
A B
0 7 3
1 2 1
2 8 1
Use DataFrame.add
:使用
DataFrame.add
:
df = df1.add(df2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.