计算列中布尔值从 True 变为 False 的次数 [英] Counting the amount of times a boolean goes from True to False in a column
问题描述
我在数据框中有一列填充了布尔值,我想计算它从 True 变为 False 的次数.
I have a column in a dataframe which is filled with booleans and i want to count how many times it changes from True to False.
当我将布尔值转换为 1 和 0 时,我可以这样做,然后使用 df.diff
然后将该答案除以 2
I can do this when I convert the booleans to 1's and 0's ,then use df.diff
and then divide that answer by 2
import pandas as pd
d = {'Col1': [True, True, True, False, False, False, True, True, True, True, False, False, False, True, True, False, False, True, ]}
df = pd.DataFrame(data=d)
print(df)
0 True
1 True
2 True
3 False
4 False
5 False
6 True
7 True
8 True
9 True
10 False
11 False
12 False
13 True
14 True
15 False
16 False
我的预期结果是False 出现的次数是 3
推荐答案
您可以执行 Col1
的按位和 带有一个掩码,指示连续行中发生更改的位置:
You can perform a bitwise and
of the Col1
with a mask indicating where changes occur in successive rows:
(df.Col1 & (df.Col1 != df.Col1.shift(1))).sum()
3
其中掩码是通过将 Col1
与自身的移位版本进行比较而获得的 (pd.shift
):
Where the mask, is obtained by comparing Col1
with a shifted version of itself (pd.shift
):
df.Col1 != df.Col1.shift(1)
0 True
1 False
2 False
3 True
4 False
5 False
6 True
7 False
8 False
9 False
10 True
11 False
12 False
13 True
14 False
15 False
16 False
17 False
Name: Col1, dtype: bool
对于多列,你可以做完全相同的(这里我用与 col1
相同的 col2
测试)
For multiple columns, you can do exactly the same (Here I tested with a col2
identical to col1
)
(df & (df != df.shift(1))).sum()
Col1 3
Col2 3
dtype: int64
这篇关于计算列中布尔值从 True 变为 False 的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!