英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论