在numpy数组中查找False-True过渡 [英] Finding False-True transitions in a numpy array
问题描述
给出一个numpy数组:
Given a numpy array:
x = np.array([False, True, True, False, False, False, False, False, True, False])
如何查找值从False转换为True的次数? 对于上面的示例,答案是2.我不要在计数中包括从True到False的转换.
How do I find the number of times the values transitions from False to True? For the above example, the answer would be 2. I don't want to include transitions from True to False in the count.
从答案到我如何确定布尔数组中的值序列?,下面的代码将生成将要更改值的索引,这不是我想要的,因为其中包括True-False转换.
From the answers to How do I identify sequences of values in a boolean array?, the following produces the indices at which the values are about to change, which is not what I want as this includes True-False transitions.
np.argwhere(np.diff(x)).squeeze()
# [0 2 7 8]
我知道这可以通过遍历数组来完成,但是我想知道是否有更快的方法?
I know that this can be done by looping through the array, however I was wondering if there was a faster way to do this?
推荐答案
获取一次性切片-x[:-1]
(从第一个elem开始并在倒数第二个elem中结束)和x[1:]
(从第二个elem开始并进行到最后),然后寻找第一个小于第二个的切片,即捕获[False, True]
的模式,最后使用ndarray.sum()
或np.count_nonzero()
-
Get one-off slices - x[:-1]
(starting from the first elem and ending in second last elem) and x[1:]
(starting from the second elem and going on until the end), then look for the first slice being lesser than the second one, i.e. catch the pattern of [False, True]
and finally get the count with ndarray.sum()
or np.count_nonzero()
-
(x[:-1] < x[1:]).sum()
np.count_nonzero(x[:-1] < x[1:])
另一种方法是寻找第一个切片为False
,第二个切片为True
,再次想到的是捕捉[False, True]
-
Another way would be to look for the first slice being False
and the second one as True
, the idea again being to catch that pattern of [False, True]
-
(~x[:-1] & x[1:]).sum()
np.count_nonzero(~x[:-1] & x[1:])
这篇关于在numpy数组中查找False-True过渡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!