numpy的有logical_or
,logical_xor
和logical_and
其中有一个reduce
方法
>> np.logical_or.reduce(a, axis=0)
array([ True, False, False, False, False, False, False, False], dtype=bool)
,你看到的例子,他们逼迫到bool
D型,所以如果你需要uint8
你在施放回结束。
由于bools以字节存储,因此您可以使用便宜的视频广播。
与axis
关键字你可以选择沿哪个轴减少。有可能选择多个轴
>> np.logical_or.reduce(a, axis=1)
array([ True, True, True, True], dtype=bool)
>>> np.logical_or.reduce(a, axis=(0, 1))
True
的keepdims
关键字是用于广播有用的,例如,以找到所有的“交叉”的行和列> = 2的阵列b
>>> b = np.random.randint(0,10, (4, 4))
>>> b
array([[0, 5, 3, 4],
[4, 1, 5, 4],
[4, 5, 5, 5],
[2, 4, 6, 1]])
>>> rows = np.logical_and.reduce(b >= 2, axis=1, keepdims=True)
# keepdims=False (default) -> rows.shape==(4,) keepdims=True -> rows.shape==(4, 1)
>>> cols = np.logical_and.reduce(b >= 2, axis=0, keepdims=True)
# keepdims=False (default) -> cols.shape==(4,) keepdims=True -> cols.shape==(1, 4)
>>> rows & cols # shapes (4, 1) and (1, 4) are broadcast to (4, 4)
array([[False, False, False, False],
[False, False, False, False],
[False, False, True, False],
[False, False, False, False]], dtype=bool)
通知轻微滥用&
运营商,代表bitwise_and
。由于效果上的bool相同的(事实上是在试图在这个地方使用and
会抛出异常),这是常见的做法
为@ajcr指出流行np.any
和np.all
是np.logical_or.reduce
和np.logical_and.reduce
速记。 但是请注意,有细微的差别
>>> np.logical_or.reduce(a)
array([ True, False, False, False, False, False, False, False], dtype=bool)
>>> np.any(a)
True
OR:如果你想坚持uint8
,并确切地知道你所有的作品将是0和1,您可以使用bitwise_and
,bitwise_or
和bitwise_xor
>>> np.bitwise_or.reduce(a, axis=0)
array([1, 0, 0, 0, 0, 0, 0, 0], dtype=uint8)
是:查看[here](http://stackoverflow.com/a/20528566/3923281),具体是关于ufuncs的'.reduce'方法的细节。 –
你可以使用'numpy.apply_along_axis()'https://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html – ZdaR