简体   繁体   English

逻辑与嵌套布尔数组

[英]logical_and with nested boolean arrays

I have one (very long) boolean array a with k True entries, and one boolean array b of length k .我有一个(很长)布尔数组ak True条目,以及一个长度为k布尔数组b I would like to get a boolean array c that is True if and only if a "and" b are True :我想获得一个布尔阵列cTrue当且仅当a “和” bTrue

import numpy

a = numpy.array([False, False, True, False, True, False])
b = numpy.array([True, False])

assert numpy.sum(a) == len(b)  # guaranteed

c = numpy.zeros(len(a), dtype=bool)
idx_b = 0
for k in range(len(a)):
    if a[k]:
        if b[idx_b]:
            c[k] = True
        idx_b += 1

print(c)
[False False  True False False False]

This here uses a loop, but I'm thinking there must a faster way with boolean indexing, but I can't quite get to it.这里使用了一个循环,但我认为必须有一种更快的布尔索引方式,但我不太明白。

Any hints?任何提示?

Simply mask input array with itself ( self-masking?) and assign -简单地用它自己屏蔽输入数组(自我屏蔽?)并分配 -

a[a] = b

If you need output in a new array, copy the input array and perform masking on the same.如果需要在新数组中输出,请复制输入数组并对其进行屏蔽。

If the assertion holds true, you can use np.flatnonzero如果断言成立,您可以使用np.flatnonzero

import numpy as np

a = np.array([False, False, True, False, True, False])
b = np.array([True, False])

assert np.sum(a) == len(b)

c = np.copy(a)
idx = np.flatnonzero(c) 
c[idx] = b

print(c)

Out:出去:

[False, False,  True, False, False, False]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM