Flip flop mechanism in pandas

huangapple go评论65阅读模式
英文:

Flip flop mechanism in pandas

问题

data3 是我想创建的输出

当 data1 为 1 时,data3 = 1。然后保持为 1,直到 data2 发出信号为 1。然后继续为 0,直到 data1 再次发出信号为 1...等等...

我可以使用 .iterrows(),但我想知道是否有更快的向量化方法?

data1 = [1,1,0,0,0,1,0,0,0,0,1]
data2 = [0,0,1,0,0,0,0,0,1,1,0]
data3 = [1,1,0,0,0,1,1,1,0,0,1]

df = pd.DataFrame()
df["d1"] = data1
df["d2"] = data2
英文:

I am looking for a flip flop type mechanism in pandas.

data3 is the output I'd like to create

data3 = 1 when data1 is a 1. Then stay a 1 until data2 signals a 1. Then continue as 0 until data1 signals a 1 again....etc.....

I could use .iterrows(), but I am wondering if there is a faster vectorized way?

data1 = [1,1,0,0,0,1,0,0,0,0,1]
data2 = [0,0,1,0,0,0,0,0,1,1,0]
data3 = [1,1,0,0,0,1,1,1,0,0,1]

df = pd.DataFrame()
df["d1"]= data1
df["d2"]= data2

答案1

得分: 1

以下是您提供的代码的翻译部分:

一种选项:

df['out'] = (
 df['d1'].map({1: True})
 .fillna(df['d2'].map({1: False}))
 .ffill().fillna(0).astype(int)
 )

print(df)

如果在相等的情况下要优先选择d2:

df['out'] = (
 df['d2'].map({1: False})
 .fillna(df['d1'].map({0: True}))
 .ffill().fillna(0).astype(int)
 )

输出:

    d1  d2  out
0    1   0    1
1    1   0    1
2    0   1    0
3    0   0    0
4    0   0    0
5    1   0    1
6    0   0    1
7    0   0    1
8    0   1    0
9    0   1    0
10   1   0    1
英文:

One option:

df['out'] = (
 df['d1'].map({1: True})
 .fillna(df['d2'].map({1: False}))
 .ffill().fillna(0).astype(int)
 )

print(df)

If you want to give priority to d2 over d1 in case of equality:

df['out'] = (
 df['d2'].map({1: False})
 .fillna(df['d1'].map({0: True}))
 .ffill().fillna(0).astype(int)
 )

Output:


    d1  d2  out
0    1   0    1
1    1   0    1
2    0   1    0
3    0   0    0
4    0   0    0
5    1   0    1
6    0   0    1
7    0   0    1
8    0   1    0
9    0   1    0
10   1   0    1

huangapple
  • 本文由 发表于 2023年2月6日 16:32:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定