Home > Enterprise >  how to sum up columns from different dataframes into a single dataframe in pandas
how to sum up columns from different dataframes into a single dataframe in pandas

Time:06-24

Sample data

import pandas as pd

df1 = pd.DataFrame() 
df1["Col1"] = [0,2,4,6,2] 
df1["Col2"] = [5,1,3,4,0]
df1["Col3"] = [8,0,5,1,7]
df1["Col4"] = [1,4,6,0,8]
#df1_new = df1.iloc[:, 1:3]

df2 = pd.DataFrame() 
df2["Col1"] = [8,2,4,6,2,3,5] 
df2["Col2"] = [3,7,3,4,0,6,8]
df2["Col3"] = [5,0,5,1,7,9,1]
df2["Col4"] = [0,4,6,0,8,6,0]
#df2_new = df1.iloc[:, 1:3]

dataframes = [df1, df2]

for df in dataframes:
    df_new=df.iloc[:, 1:3]
    print(df_new.sum(axis=0))

result from above looks like this:

Col2    13  
Col3    21  
dtype: int64
Col2    31  
Col3    28  
dtype: int64

But how can I sum up both dataframes and put it into a single one?

Result should look like this:

enter image description here

CodePudding user response:

You can either sum the dataframes separately and then add the results, or sum the concatenated dataframes:

df1.iloc[:,1:3].sum()   df2.iloc[:,1:3].sum()

pd.concat([df1,df2]).iloc[:,1:3].sum()

In both cases the result is

Col2    44
Col3    49
dtype: int64

CodePudding user response:

Get the columnwise sums of both dataframes, take the middle two columns of each, and add them together. Then, transpose the result to turn the rows into columns:

(df1.iloc[:, 1:3].sum()   df2.iloc[:, 1:3].sum())).T

This outputs:

   Col2  Col3
0    44    49

CodePudding user response:

Here is one way:

print((df1[["Col2", "Col3"]]   df2[["Col2", "Col3"]]).sum().to_frame().T)

Or, if you need to use iloc for the columns, here is another way:

print((df1.iloc[:, 1:3]   df2.iloc[:, 1:3]).sum().to_frame().T)

Output (same for both):

   Col2  Col3
0  30.0  39.0
  • Related