Home > Enterprise >  Pandas group by and row count by category
Pandas group by and row count by category

Time:07-26

I have a pandas df as follows:

User   Amount   Type
100     10      Check
100     20      Cash
100     30      Paypal
200     50      Venmo
200     50      Cash
200     50      Check
300     20      Zelle
300     15      Zelle
300     15      Zelle

I want to organize it such that my end result is as follows:

User     Cash     Check  Paypal   Venmo  Zelle
100       1        1      1
200       1        1                1
300                                        3

I am looking to count the number of times a user has transacted through each unique method. If a user didnt transact, I want to either leave it blank or set it to 0. How can I do this? I tried a pd.groupby() but am not sure of the next step... Thanks!

CodePudding user response:

You are looking for crosstab:

pd.crosstab(df['User'], df['Type']).reset_index().rename_axis('',axis=1)

output:

   User  Cash  Check  Paypal  Venmo  Zelle
0   100     1      1       1      0      0
1   200     1      1       0      1      0
2   300     0      0       0      0      3
  • Related