slickspidey
slickspidey

Reputation: 69

How to sum multiple columns to get a "groupby" type of output with Python?

The database I'm working with is a little strange but I basically just want to get a sum of each column and output it into a data frame similar to groupbys layout. My current dataframe is like this:

Diet Kin LLFC MH Nursing
1          1   3    1
1     1    1   1    1
1     2    1   3    1
1     2    1   6    1

I'd essentially like to sum the columns and output something like this:

Diet    4
Kin     5
LLFC    4
MH      13
Nursing 4

I tried to do a groupby but I got a valueerror that grouper and axis must be the same length. I added a total row that sums every column up, but I still am finding trouble to just output a small summary data frame like the one I would like above. Can someone help?

Upvotes: -1

Views: 116

Answers (1)

Aditya
Aditya

Reputation: 1377

To achieve this you can simply use df.sum() which will give you:

Diet        4.0
Kin         5.0
LLFC        4.0
MH         13.0
Nursing     4.0
dtype: float64

To get the results in transposed form:

df_sum = pd.DataFrame(df.sum()).T

>>>>    Diet    Kin     LLFC    MH  Nursing
     0  4.0     5.0     4.0     13.0    4.0

Upvotes: 2

Related Questions