gpt4 book ai didi

python - 如何创建基于逻辑 : (0 followed by a 1 is True. 的 bool 系列 A 1 前面有 0 是 True。其他都是假的)

转载 作者:行者123 更新时间:2023-12-01 13:11:51 24 4
gpt4 key购买 nike

我有以下 DF。我正在尝试制作逻辑为的 bool 系列:(0 后跟 1 为 True。1 前跟 0 为 True。所有其他均为 False)

这是数据框

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 为 True。1 前跟 0 为 True。所有其他均为 False:

    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,但是只有在后面跟着 1 而不是另一个零时,零才应该是 True。任何帮助,将不胜感激。谢谢。

最佳答案

尝试:

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 组合两个条件。

关于python - 如何创建基于逻辑 : (0 followed by a 1 is True. 的 bool 系列 A 1 前面有 0 是 True。其他都是假的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59382223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com