简体   繁体   中英

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

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

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

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

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

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