基于逻辑创建布尔序列的方法:(0后面跟着1为True。0前面跟着1为True。其他情况都为False)

3
我有以下数据框。我尝试创建一个布尔序列,逻辑是: (0后面跟着1为真。0前面跟着1为真。其他情况都为假)
这是数据框:
df = pd.DataFrame({'A': {0: 1, 1: 0, 2: 1, 3: 1, 4: 1, 5: 0, 6: 1, 7: 1, 8: 1, 9: 1, 10: 0, 11: 0, 12: 1}})                                                                                                                                                                                 

    A
0   1
1   0
2   1
3   1
4   1
5   0
6   1
7   1
8   1
9   1
10  0
11  0
12  1

期望输出(0后面跟着1为真。0前面跟着1为真。其他情况为假):
    A  Truth
0   1  False
1   0   True
2   1   True
3   1  False
4   1  False
5   0   True
6   1   True
7   1  False
8   1  False
9   1  False
10  0  False
11  0   True
12  1   True

我的输出使用:df['Truth'] = df['A'] == 0 | ((df['A'].shift() == 0) & (df['A'] == 1))
    A  Truth
0   1  False
1   0   True
2   1   True
3   1  False
4   1  False
5   0   True
6   1   True
7   1  False
8   1  False
9   1  False
10  0   True
11  0   True
12  1   True

我在零上得到了 True,但只有在零后面跟着一时才应该是 True,而不是另一个零。如果能提供任何帮助将不胜感激。谢谢。
3个回答

1
在你的情况下,滚动总和应该为1。
df.A.rolling(2).sum()==1

0   False
1    True
2    True
3   False
4   False
5    True
6    True
7   False
8   False
9   False
10   True
11  False
12   True

10和11应该交换。在我的测试中,我也得到了这个结果 :-) 10应该是False,而11应该是True。 - oppressionslayer

1
你可以使用你的逻辑:
df['A'] != df['A'].shift(fill_value=df['A'].iloc[0])

输出:

0     False
1      True
2      True
3     False
4     False
5      True
6      True
7     False
8     False
9     False
10     True
11    False
12     True
Name: A, dtype: bool

10和11应该交换。我在测试中也遇到了这个问题 :-) 10应该是False,而11应该是True。 - oppressionslayer

1

尝试:

cond1 = df['A'].diff().shift(-1).eq(1).where(df['A']==0)
df['Truth'] = df['A'].diff().eq(1).where(df['A'] == 1).fillna(cond1).astype('bool')
print(df)

输出:

    A  Truth
0   1  False
1   0   True
2   1   True
3   1  False
4   1  False
5   0   True
6   1   True
7   1  False
8   1  False
9   1  False
10  0  False
11  0   True
12  1   True

检查条件1,仅在A == 0时设置它,然后检查条件2,仅在A == 1时设置它,使用fillna来组合这两个条件。


1
谢谢Scott,这对我很有用!我尝试了不同的布尔等式,但这个有效! - oppressionslayer
是的...这个可能可以进行优化。但使用diff有助于逻辑。 - Scott Boston

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接