Python Numpy:布尔数组中True值的开始/结束索引[重复]

guicsvcw  于 2023-04-30  发布在  Python
关注(0)|答案(2)|浏览(140)

此问题已在此处有答案

Finding contiguous regions in a 1D boolean array(6个回答)
昨天关门了。
晚上好
有没有一种有效的方法来获取布尔数组中True值的所有开始和结束索引?假设我有这个数组:

x = np.array([nan, 11, 13, nan, nan, nan, 9, 3, nan, 3, 4, nan])

我使用np.isnan(x),得到:

[True, False, F, T, T, T, F, F, T, F, F, T]

我想在最后有一个数组或列表,只有NaN-〉i的索引。如果是单个,则为一个索引,或者如果是连续的NaN值,则为开始索引和结束索引:[0, [3, 5], 8, 11]
我必须自己在数组上循环并编写一个函数吗?或者有一种既简单又有效的方法吗?
我已经运行了一些东西,但由于我必须处理每个数组和多个数组的数十万个值,这需要时间。

j0pj023g

j0pj023g1#

您可以从itertools模块使用groupby

lst = []
for mask, grp in groupby(zip(np.arange(len(x)), np.isnan(x)), key=lambda x: x[1]):
    if mask == True:  # only for NaN
        idx = [idx for idx, _ in grp]
        lst.append([idx[0], idx[-1]] if len(idx) > 1 else idx[0])

输出:

>>> lst
[0, [3, 5], 8, 11]
cdmah0mi

cdmah0mi2#

您可以使用布尔运算将np.isnan输出在左/右移位:

# if the value a NaN?
m = np.isnan(x)
# is the preceding value not a NaN?
m2 = np.r_[False, ~m[:-1]]
# is the following value not a NaN?
m3 = np.r_[~m[1:], False]

out = np.where((m&m2)|(m&m3))[0]

输出:

array([ 0,  3,  5,  8, 11])

相关问题