![](/img/trans.png)
[英]Python Dataframe select last n rows based on present value condition
[英]python dataframe timeseries check if value changed more than x in last n rows and forward n rows
我有來自現場的陽光數據。 我正在檢查陽光在過去 1 分鍾和未來 1 分鍾內的變化是否超過一個值。 下面我舉一個例子。 我在哪里檢查數據值在過去 10 秒內是否變化超過 4。 代碼:
xdf = pd.DataFrame({'data':np.random.randint(10,size=10)},index=pd.date_range('2022-06-03 00:00:00', '2022-06-03 00:00:45', freq='5s'))
# here data frequency 5s, so, to check last 10s
# I have to consider present row and last 2 rows
# Perform rolling max and min value for 3 rows
nrows = 3
# Allowable change
ac = 4
xdf['back_max'] = xdf['data'].rolling(nrows).max()
xdf['back_min'] = xdf['data'].rolling(nrows).min()
xdf['back_min_max_dif'] = (xdf['back_max'] - xdf['back_min'])
xdf['back_<4'] = (xdf['back_max'] - xdf['back_min']).abs().le(ac)
print(xdf)
## Again repeat the above for the future nrows
## Don't know how?
預期輸出:
data back_max back_min back_min_max_dif back_<4
2022-06-03 00:00:00 7 NaN NaN NaN False
2022-06-03 00:00:05 7 NaN NaN NaN False
2022-06-03 00:00:10 5 7.0 5.0 2.0 True
2022-06-03 00:00:15 8 8.0 5.0 3.0 True
2022-06-03 00:00:20 6 8.0 5.0 3.0 True
2022-06-03 00:00:25 2 8.0 2.0 6.0 False
2022-06-03 00:00:30 3 6.0 2.0 4.0 True
2022-06-03 00:00:35 1 3.0 1.0 2.0 True
2022-06-03 00:00:40 5 5.0 1.0 4.0 True
2022-06-03 00:00:45 5 5.0 1.0 4.0 True
有沒有辦法可以簡化上述程序? 另外,我必須為未來的 nrows 執行最大滾動,如何?
對於未來/向前滾動,您可以滾動反向數據。 這可能不適用於時間窗口滾動:
rolling = xdf['data'].rolling(nrows)
xdf['pass_<'] = (rolling.max()-rolling.min()).le(ac)
future_roll = xdf['data'][::-1].rolling(nrows)
xdf['future_<'] = future_roll.max().sub(future_roll.min()).le(ac)
輸出:
data pass_< future_<
2022-06-03 00:00:00 7 False True
2022-06-03 00:00:05 7 False True
2022-06-03 00:00:10 5 True True
2022-06-03 00:00:15 8 True False
2022-06-03 00:00:20 6 True True
2022-06-03 00:00:25 2 False True
2022-06-03 00:00:30 3 True True
2022-06-03 00:00:35 1 True True
2022-06-03 00:00:40 5 True False
2022-06-03 00:00:45 5 True False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.