-1

I have a dataframe that looks like this:

    time    amount  user 
0   2020-06     1   A
1   2020-06     1   B
2   2020-04     1   C
3   2020-04     2   A
4   2020-02     1   C

I want to make something like that:

    2020-02 2020-04 2020-06
A   0       2       1
B   0       0       1
C   1       1       0

I am using this code

df.groupby(['user','time'])['amount'].sum()
df.unstack().fillna(0).reset_index()

but I am getting wrong results. Is my code correct?

bitmover
  • 97
  • 2
  • 8
  • `df.pivot(index='user',columns='time',values='amount').fillna(0)`? Or `df.pivot_table` with `aggfunc='sum'` if you have values to aggregate. – Ch3steR Jun 16 '20 at 17:56
  • Change this in your code `df.groupby(['user','time'])['amount'].sum().unstack(fill_value=0)` – Ch3steR Jun 16 '20 at 17:59

1 Answers1

2

Use this:

df.set_index(['user','time'])['amount'].unstack(fill_value=0)

Output:

time  2020-02  2020-04  2020-06
user                           
A           0        2        1
B           0        0        1
C           1        1        0
Scott Boston
  • 147,308
  • 15
  • 139
  • 187