通过比较两列来跟踪 pandas 的状态反转 [英] track state reversal in Pandas by comparing two columns
问题描述
This is a follow-on to my previous question: detecting value crossing between columns in Pandas
假设我有两列df['a']
和df['b']
,为简化起见,在此分别称为'a'和'b'
Let's assume I have two columns, df['a']
and df['b']
, called 'a' and 'b' here to simplify
在上一个问题中,我试图检测以下位置的索引:a [i-1]< b [i]和a [i]> = b [i]
In the previous question, I was trying to detect indices where: a[i - 1] < b[i] and a[i] >= b[i]
现在,我正在尝试跟踪两个更改:
now, I am trying to track two changes:
a[i - 1] < b[i] and a[i] >= b[i]
和
a[i - 1] >= b[i] and a[i] < b[i]
并创建一个基于最后发生的更改设置值的列.
and create a column with a value set based on the LAST change that occurred.
这是一些伪代码:
state = 0
result = []
for i in myIndex:
if a[i - 1] < b[i] and a[i] >= b[i]:
state = 1
elif a[i - 1] >= b[i] and a[i] < b[i]:
state = 0
result.append(state)
在Pandas中是否有惯用的(非循环)方式来实现这一目标?
is there an idiomatic (non-looping) way to achieve this in Pandas?
我知道这个问题引起了一些混乱,所以我没有正确说出它.此处的示例:
I realize this question has caused some confusion, so I didn't word it properly. An example here:
假设我有两列用于跟踪的两个条件的输出:
Let's assume I have two columns for the outputs of the two conditions I'm tracking:
cond_A cond_B
false false
false true
false false
false false
true false
false false
然后输出应该是(如果我们将0和1设置为输出值):
then the output should be (if we set 0 and 1 as output values):
cond_A cond_B output
false false 0
false true 1
false false 1
false false 1
true false 0
false false 0
因此,如果两个条件都为假,则我们将重用最后一个状态,如果条件为真,则将设置状态.
so, if both conditions are false, we reuse the last state, if a condition is true, we set the state.
推荐答案
this is the equation of a RS flip flop: https://en.wikipedia.org/wiki/Flip-flop_(electronics)
使用给出的示例作为数据框:
using the example given as a dataframe:
print(df)
cond_A cond_B
0 False False
1 False True
2 False False
3 False False
4 True False
5 False False
更新
df['state']=df.any(axis=1).where(df['cond_B'].cumsum().ge(1),0).cumsum()%2
print(df)
cond_A cond_B state
0 False False 0
1 False True 1
2 False False 1
3 False False 1
4 True False 0
5 False False 0
如果您有两个独立的系列
If you have two independent series
(cond_A | cond_B).where(cond_B.cumsum().ge(1),0).cumsum()%2
这篇关于通过比较两列来跟踪 pandas 的状态反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!