![](/img/trans.png)
[英]django template boolean variable shows as 0 but is considred True. Why?
[英]How to create a Boolean Series based on the logic: (0 followed by a 1 is True. A 1 preceded by a 0 is True. All others are False)
我有以下 DF。 我正在尝试制作一个布尔系列,其中的逻辑是:(0 后跟 1 是真。1 前跟 0 是真。所有其他都是假)
这是数据框
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 是真。1 前跟 0 是真。所有其他都是假:
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 表示,而不是另一个零。 任何帮助,将不胜感激。 谢谢。
在你的情况下rolling
sum
应该是 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
您可以使用您的逻辑:
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
尝试:
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 组合两个条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.