Home > Enterprise >  How to group by 2 columns with counts in Panda?
How to group by 2 columns with counts in Panda?

Time:11-19

This is the Table:

NAME: DATE:
Apple 2022-10-04
Apple 2022-10-04
Apple 2022-10-04
Orange 2022-10-04
Apple 2022-10-06
Apple 2022-10-06
Apple 2022-10-06

I would like to group by name & date, and also add a column called 'Counts'.

OUTCOME that I wanna look like:

NAME: DATE: COUNTS:
Apple 2022-10-04 3
Orange 2022-10-04 1
Apple 2022-10-06 3

CodePudding user response:

One way to do it:

df.groupby(['NAME', 'DATE']).DATE.agg('count').to_frame('COUNTS').reset_index()

Output:

     NAME        DATE  COUNTS
0   apple  2022-10-04       3
1   apple  2022-10-06       3
2  orange  2022-10-04       1

CodePudding user response:

Another possible solution:

df.value_counts(['NAME', 'DATE']).rename('COUNTS').reset_index()

Output:

     NAME        DATE  COUNTS
0   Apple  2022-10-04       3
1   Apple  2022-10-06       3
2  Orange  2022-10-04       1
  • Related