简体   繁体   中英

How can I add two pandas.DataFrames cellwise?

I have a bunch of pandas.DataFrame s which are each a table of counts . 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. 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 :

df = df1.add(df2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM