我在数据框中有一列,其中填充了 bool 值,我想计算它从 True 变为 False 的次数。
当我将 bool 值转换为 1 和 0 时,我可以这样做,然后使用 df.diff
然后将该答案除以 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
最佳答案
您可以执行 bitwise and
Col1
的一个掩码,指示连续行中发生更改的位置:
(df.Col1 & (df.Col1 != df.Col1.shift(1))).sum()
3
掩码是通过将 Col1
与其自身的移位版本 ( 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
)
(df & (df != df.shift(1))).sum()
Col1 3
Col2 3
dtype: int64
关于python - 计算列中 bool 值从 True 变为 False 的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54219948/