【问题标题】:Rolling count specific numberRolling count specific number
【发布时间】: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?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    You can use:

    (df.assign(Count_0_last_15_min=df['Data'].eq(0))
       .groupby('Group', as_index=False)
       .rolling(3, min_periods=1)['Count_0_last_15_min'].sum()
       .droplevel(0)
    )
    

    Output:

    0     1.0
    1     2.0
    2     2.0
    3     1.0
    4     0.0
    5     1.0
    6     1.0
    7     2.0
    8     0.0
    9     1.0
    10    1.0
    11    1.0
    12    1.0
    13    2.0
    14    2.0
    15    1.0
    Name: Count_0_last_15_min, dtype: float64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 2021-04-23
      • 2021-12-09
      • 2022-12-01
      • 1970-01-01
      • 2012-01-04
      • 2020-11-12
      相关资源
      最近更新 更多