简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM