簡體   English   中英

Pandas - 滾動 window 計數條件

[英]Pandas - Rolling window count with condition

在 Pandas 滾動 window 計數中,如何根據給定條件僅對 select 進行某些行? 我在文檔或其他問題中沒有找到任何解決方案。

使用以下 dataframe:

random.seed(42)
date_0 = datetime.datetime(2020, 1, 1, 0, 0, 0, 0)
dates = [date_0 + datetime.timedelta(seconds=random.uniform(0, 120)) for i in range(500)]
dates.sort()
speeds = [random.uniform(1, 10) for i in range(500)]
speeds.sort()
pressures = [i**2 + random.normalvariate(0, 1) for i in speeds]
data = [speeds, pressures]
df = pd.DataFrame(data=list(zip(speeds, pressures)), columns=['speed', 'pressure'], index=dates)
dates_1 = random.sample(dates, int(len(dates) * 0.6))
df.loc[:, 'controlled'] = False
df.loc[dates_1, 'controlled'] = True
df.loc[:, 'rolling_obs_count'] = df.loc[:, 'speed'].rolling(window=str(1) + 's').count()
print('df: \n', df)
df: 
                                speed    pressure  controlled  rolling_obs_count
2020-01-01 00:00:00.048713  1.024082    4.491483        True                1.0
2020-01-01 00:00:00.068628  1.084577    0.773474        True                2.0
2020-01-01 00:00:00.202953  1.091360    0.584872        True                3.0
2020-01-01 00:00:00.425483  1.125268    2.361184       False                4.0
2020-01-01 00:00:00.665378  1.127335    2.050226        True                5.0
...                              ...         ...         ...                ...
2020-01-01 00:01:59.531574  9.945263   98.811644        True                5.0
2020-01-01 00:01:59.534566  9.976833   99.481287       False                6.0
2020-01-01 00:01:59.704513  9.990121   99.452698       False                6.0
2020-01-01 00:01:59.814533  9.996152   99.479074        True                6.0
2020-01-01 00:01:59.913896  9.999170  100.584748        True                7.0

計數 function 計算滾動 window 中的所有行,我只需要計算“受控”列為“真”的行。 我怎樣才能做到這一點?

也許很簡單:

>>> df.rolling('1s')['controlled'].sum()
2020-01-01 00:00:00.048713    1.0
2020-01-01 00:00:00.068628    2.0
2020-01-01 00:00:00.202953    3.0
2020-01-01 00:00:00.425483    3.0
2020-01-01 00:00:00.665378    4.0
                             ... 
2020-01-01 00:01:59.531574    5.0
2020-01-01 00:01:59.534566    5.0
2020-01-01 00:01:59.704513    4.0
2020-01-01 00:01:59.814533    4.0
2020-01-01 00:01:59.913896    5.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM