【发布时间】:2022-12-01 19:11:57
【问题描述】:
Suppose I have dataframe "df" like this
| Time | Group | Data |
|---|---|---|
| 2022-10-01 00:05:00 | A | 0 |
| 2022-10-01 00:10:00 | A | 0 |
| 2022-10-01 00:15:00 | A | 1 |
| 2022-10-01 00:20:00 | A | 1 |
| 2022-10-01 00:25:00 | A | 1 |
| 2022-10-01 00:30:00 | A | 0 |
| 2022-10-01 00:35:00 | A | 1 |
| 2022-10-01 00:40:00 | A | 0 |
| 2022-10-01 00:05:00 | B | 11 |
| 2022-10-01 00:10:00 | B | 0 |
| 2022-10-01 00:15:00 | B | 12 |
| 2022-10-01 00:20:00 | B | 13 |
| 2022-10-01 00:25:00 | B | 0 |
| 2022-10-01 00:30:00 | B | 0 |
| 2022-10-01 00:35:00 | B | 15 |
| 2022-10-01 00:40:00 | B | 16 |
Assume That I already sort out data by Group and Time already I would love to count occurence of 0 in previous 15 minutes include itself
Which result should be like
| Time | Group | Data | Count_0_last_15_min |
|---|---|---|---|
| 2022-10-01 00:05:00 | A | 0 | 1 |
| 2022-10-01 00:10:00 | A | 0 | 2 |
| 2022-10-01 00:15:00 | A | 1 | 2 |
| 2022-10-01 00:20:00 | A | 1 | 1 |
| 2022-10-01 00:25:00 | A | 1 | 0 |
| 2022-10-01 00:30:00 | A | 0 | 1 |
| 2022-10-01 00:35:00 | A | 1 | 1 |
| 2022-10-01 00:40:00 | A | 0 | 2 |
| 2022-10-01 00:05:00 | B | 11 | 0 |
| 2022-10-01 00:10:00 | B | 0 | 1 |
| 2022-10-01 00:15:00 | B | 12 | 1 |
| 2022-10-01 00:20:00 | B | 13 | 1 |
| 2022-10-01 00:25:00 | B | 0 | 1 |
| 2022-10-01 00:30:00 | B | 0 | 2 |
| 2022-10-01 00:35:00 | B | 0 | 3 |
| 2022-10-01 00:40:00 | B | 16 | 2 |
currently I try to use rolling to get data from each from previous record
df.groupby('Group')['Data'].rolling(3,min_periods=1)
however I stuck after rolling part to only counting "0" occurrence ( I did try .eq(0).sum() but it can't apply with rolling() method
is there another method to group by and rolling count for this solution?
【问题讨论】: