Group by date and count of categorical variable date wise

38 Views Asked by At

Date frame having two categorical variable column with date time stamp.

Date Time Va Vb
01-01-2023 05:55 A B
01-01-2023 06:25 A
01-01-2023 17:42 B
01-01-2023 19:17 A B
02-01-2023 05:55 A B
02-01-2023 06:25 A B
02-01-2023 17:42 A B
02-01-2023 19:17 A

To group by the set by date and count Va and Vb for a date. Expected Result:

Va Vb
01-01-2023 3 3
02-01-2023 4 3

Wrote in previous slide

2

There are 2 best solutions below

1
Cetin Basoz On

If you are using an SQL database (and those empty values are NULL):

Select Date, Count(Va) as Va, Count(Vb) as Vb 
  from sourceTable 
  group by date;

DBFiddle demo

0
Andrej Kesely On

Try:

out = df[['Date', 'Va', 'Vb']].groupby('Date').count()
print(out)

Prints:

            Va  Vb
Date              
01-01-2023   3   3
02-01-2023   4   3