user3142067
user3142067

Reputation: 1292

Summing columns to form a new dataframe

I have a DataFrame

                A              B             C            D
2015-07-18  4.534390e+05  2.990611e+05  5.706540e+05  4.554383e+05   
2015-07-22  3.991351e+05  2.606576e+05  3.876394e+05  4.019723e+05   
2015-08-07  1.085791e+05  8.215599e+04  1.356295e+05  1.096541e+05   
2015-08-19  1.397305e+06  8.681048e+05  1.672141e+06  1.403100e+06  
...

I simply want to sum all columns to get a new dataframe

      A   B  C  D
sum   s   s  s  s 

With the columnwise sums And then print it with to_csv(). When is use

 df.sum(axis=0)
 print(df)


 A       9.099377e+06
 B       5.897003e+06
 C       1.049932e+07
 D       9.208681e+06
 dtype: float64

Upvotes: 11

Views: 437

Answers (4)

JoeCondron
JoeCondron

Reputation: 8906

I think the simplest is df.agg([sum])

df.agg([sum])
Out[40]:
            A            B          C           D
sum 2358458.2   1509979.49  2766063.9   2370164.7

Upvotes: 0

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

You can transform df.sum() to DataFrame and transpose it:

In [39]: df.sum().to_frame('sum').T
Out[39]:
             A           B          C          D
sum  2358458.2  1509979.49  2766063.9  2370164.7

Upvotes: 11

cs95
cs95

Reputation: 402523

A slightly shorter version of pd.DataFrame is (with credit to jezrael for simplification):

In [120]: pd.DataFrame([df.sum()], index=['sum'])
Out[120]: 
             A           B          C          D
sum  2358458.2  1509979.49  2766063.9  2370164.7

Upvotes: 4

jezrael
jezrael

Reputation: 862681

Use DataFrame constructor:

df = pd.DataFrame(df.sum().values.reshape(-1, len(df.columns)),
                  columns=df.columns, 
                  index=['sum'])
print (df)
             A           B          C          D
sum  2358458.2  1509979.49  2766063.9  2370164.7

Upvotes: 3

Related Questions