问题描述:
我正在试着模拟一台机器,它的运行模式"如果"VALUE"在前3个时间步中大于或等于5 -这意味着&;value&;>= 5至少3分钟。运营模式&;保持"&;B"为下一个时间步骤,只要"VALUE"大于或等于5,并变成"A"在至少3个时间步之后-这意味着操作模式&;在接下来的3分钟内保持有效。3分钟后运行模式"a";如果"VALUE">
目标:
我需要一种使用python和pandas来识别"A"描述的操作模式的方法。和";B"(列:"statusA/& "),根据列"VALUE"中的值状态"开启";和";down"(专栏:"VALUE<5—>down, VALUE>=5 ->知道;)。
必须考虑的条件如下:
- 中"A"one_answers";B">
- 中"B"如果至少3个"on">
- 一旦"B"发生,接下来的3个时间步必须是即使状态是"down",也要保持"&;B"只要"继续";存在。
What I did try:
我尝试了多种方法,为案件申请了抗辩;和";知道;并尝试根据计数器值跟踪状态,但不幸的是它没有正常工作。
修改方案. 我编辑了我的解决方案,感谢亲爱的mozway提出的一个微妙的观点:
import pandas as pd
df2['status'] = df2['VALUE'].mask(df2['VALUE'].shift().rolling(3, min_periods=3).min() >= 5, 'B')
m1 = df2['status'].shift().eq('B')
m2 = df2['status'].shift(2).eq('B')
df2['status'] = (df2['status']
.mask(m1 | m2).fillna('B')
.astype(str)
.str.replace(r'd+', 'A'))
m5 = df2['status'].shift().eq('B')
m6 = df2['status'].shift(2).eq('B')
m3 = df2['status'].eq('A')
m4 = df2.iloc[:, 2].eq('on')
df2['status'] = df2['status'].mask((m5 & m3 & m4) | (m6 & m3 & m4)).fillna('B')
index VALUE ... resulted statusA/B status
0 0 3 ... A A
1 1 5 ... A A
2 2 2 ... A A
3 3 6 ... A A
4 4 3 ... A A
5 5 1 ... A A
6 6 7 ... A A
7 7 7 ... A A
8 8 2 ... A A
9 9 2 ... A A
10 10 3 ... A A
11 11 6 ... A A
12 12 8 ... A A
13 13 8 ... A A
14 14 7 ... B B
15 15 4 ... B B
16 16 4 ... B B
17 17 6 ... A(expected is B because is "on" and at least 3... B
18 18 6 ... A(expected is B because is "on" and at least 3... B
19 19 6 ... A(expected is B because is "on" and at least 3... B
20 20 7 ... B B
21 21 2 ... B B
22 22 9 ... B B
23 23 8 ... A(expected is B because "B" keeps a "B" for 3 ... B
24 24 7 ... A(expected is B because is "on" and at least 3... B
25 25 2 ... B B
26 26 4 ... A(expected is B because "B" keeps a "B" for 3 ... B
27 27 4 ... A(expected is B because "B" keeps a "B" for 3 ... B
28 28 1 ... A(this true because it is down and the 3 time ... A
29 29 4 ... A A
[30 rows x 5 columns]