简体   繁体   中英

Using OR to reduce a 3D boolean array to 2D

I have a 3D boolean array (5830L, 6447L, 4L) which I want to reduce to (5830L, 6447L) by using OR boolean operator across the 3rd dimension (4L) . Therefore I will be doing an element by element comparison of 4L 2D arrays. A simple 1D example would be something like:

a = [True, False, True]
b = [False, False, True]
c = [True, False, True]
mask = [any(tup) for tup in zip(a, b, c)]
print mask
'True, False, True'

The size of the 3rd dimension can vary, so I need to run it in a for loop or run it in such a way that the size of the 3rd dimension isn't hardcoded as it is above. numpy.logical_or(a, b) works well, but only for 2 array elements ( 2L ).

Any ideal how to do this when its 3 or more elements; ie the 3rd dimension is > 2L ?

Two options: use the .reduce ufunc method , or use any (which is the same as a repeated OR on booleans):

In [195]: x = np.random.choice([False, True], (5830, 6447, 4))

In [196]: via_reduce = np.logical_or.reduce(x, axis=2)

In [197]: via_any = x.any(axis=2)

In [198]: via_manual = np.logical_or(np.logical_or(np.logical_or(x[..., 0], x[..., 1]), x[..., 2]), x[...,3])

In [199]: np.allclose(via_reduce, via_any)
Out[199]: True

In [200]: np.allclose(via_reduce, via_manual)
Out[200]: True

To be honest I was expecting .any to be substantially faster, but there's not much difference here:

In [201]: %timeit via_reduce = np.logical_or.reduce(x, axis=2)
883 ms ± 2.99 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [202]: %timeit via_any = x.any(axis=2)
895 ms ± 7.16 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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