简体   繁体   English

使用OR将3D布尔数组简化为2D

[英]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) . 我有一个3D布尔数组(5830L, 6447L, 4L) ,我想通过在第3维(4L)使用OR布尔运算符将其简化为(5830L, 6447L) (4L) Therefore I will be doing an element by element comparison of 4L 2D arrays. 因此,我将对4L 2D数组进行逐元素比较。 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. 第3维的大小可以变化,因此我需要在for循环中运行它,或以这样的方式运行它,即第3维的大小不像上面那样被硬编码。 numpy.logical_or(a, b) works well, but only for 2 array elements ( 2L ). numpy.logical_or(a, b)效果很好,但仅适用于2个数组元素( 2L )。

Any ideal how to do this when its 3 or more elements; 任何理想的情况,当其包含3个或更多元素时如何执行此操作; ie the 3rd dimension is > 2L ? 即三维尺寸> 2L

Two options: use the .reduce ufunc method , or use any (which is the same as a repeated OR on booleans): 两个选项:使用.reduce ufunc方法 ,或使用any 方法 (与对布尔值的重复OR相同):

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: 老实说,我期望.any会更快,但是这里并没有太大的区别:

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)

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

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