Home > Enterprise >  How to summarize rows on column in pandas dataframe
How to summarize rows on column in pandas dataframe

Time:06-24

Dataframe looks like this:

   Col2  Col3
0     5     8
1     1     0
2     3     5
3     4     1
4     0     7

How can I sum values and get rid of index. To make it looks like this?

   Col2  Col3
     13    21

Sample code:

import pandas as pd

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

print(df_new)

CodePudding user response:

Use .sum() to get the sums for each column. It produces a Series where each row contains the sum of a column. Transpose this to turn each row into a column, and then use .to_string(index=False) to print out the DataFrame without the index:

pd.DataFrame(df.sum()).T.to_string(index=False)

This outputs:

 Col2  Col3
   13    21

CodePudding user response:

You can try:

df_new.sum(axis = 0)
df_new.reset_index(drop=True, inplace=True)
  • Related