Padfoot123
Padfoot123

Reputation: 1117

Pandas group by and calculation based on condition

I have the below dataframe

DateTime              ID    Number
2020-09-01 09:30:00   1     2
2020-09-01 09:30:00   2     2
2020-09-01 10:30:00   3     2
2020-09-01 10:30:00   4     2
2020-09-01 10:30:00   5     3
2020-09-01 11:30:00   6     3

I have to group the above dataframe using Datetime column and have to perform the calculation: count of ID when Number column has value 2/Total count of ID.

Output:

DateTime             new_calculated_field
2020-09-01 09:30:00  1
2020-09-01 10:30:00  0.67
2020-09-01 11:30:00  0

Upvotes: 1

Views: 152

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

Do you mean:

df['Number'].eq(2).groupby(df['DateTime']).mean()

Output:

DateTime
2020-09-01 09:30:00    1.000000
2020-09-01 10:30:00    0.666667
2020-09-01 11:30:00    0.000000
Name: Number, dtype: float64

Upvotes: 2

Related Questions