0
votes

I have data like this:

col1 col2 col3
1 0 1
1 1 0
1 1 0
1 0 0

My desired output is:

col sum
col1 4
col2 2
col3 1

My first thought was to put the column names in a list, loop through it, and each time sum that column and union the results to a new df.

Then I thought, maybe it's possible to do multiple aggregations, e.g.:

df.agg(sum('col1), sum('col2))

... and then figure out a way to unpivot.

Is there an easier way?

1

1 Answers

1
votes

You could sum the values and reshape:

df.sum().rename('sum').rename_axis('col').reset_index()

output:

    col  sum
0  col1    4
1  col2    2
2  col3    1