thor
thor

Reputation: 281

Pandas reshape dataframe values as columns

I am struggling with a problem.

I have a pandas dataframe that looks like this:

month      code     a     b     c
2018-01-01  foo     43   34324  12
2018-01-01  bar     232  34     634
2018-01-01  gar     2312 454    243
2017-01-01  foo     12   1234   34534
2017-01-01  bar     32   34232  345
2017-01-01  gar     2323 34     234
2016-01-01  foo     908  759    342
2016-01-01  bar     4654 42     865
2016-01-01  foo     3    43    34235

I am trying to reshape my dataframe so columns 'a', 'b' and 'c' are transposed and grouped by unique months as the columns. Then I need to sum my values. I am looking for something like this:

   2016-01-01 2017-01-01 2018-01-01
a
b
c

Upvotes: 0

Views: 61

Answers (1)

Peter Leimbigler
Peter Leimbigler

Reputation: 11105

Looks like you need

df.groupby('month').sum().T

Explanation:

  1. Group by unique month.
  2. Within each group, take the sum of each column, which by default will select only columns with numeric data types. That's why the column code does not end up in the result.
  3. Transpose the result with .T

Upvotes: 3

Related Questions