2017-04-05 132 views
1

我有多个维度布尔numpy的阵列,例如,减少操作,但一个

import numpy 

a = numpy.random.rand(7, 7, 3) < 0.1 

我现在想在所有维度做一个all操作,但最后检索数组大小3.本

all_small = [numpy.all(a[..., k]) for k in range(a.shape[-1])] 

作品,但因为Python的循环是非常缓慢,如果a是长在最后一个维度。

有关如何对此进行矢量化的任何提示?

回答

3

我们可以使用axis param。因此,对于3D阵列跳过最后一个,这将是 -

a.all(axis=(0,1)) 

要处理方面的通用号码的ndarrays和沿所有轴,但指定一个执行numpy.all操作,执行将是这个样子 -

def numpy_all_except_one(a, axis=-1): 
    axes = np.arange(a.ndim) 
    axes = np.delete(axes, axis) 
    return np.all(a, axis=tuple(axes)) 

样品试验来测试所有轴 -

In [90]: a = numpy.random.rand(7, 7, 3) < 0.99 

In [91]: a.all(axis=(0,1)) 
Out[91]: array([False, False, True], dtype=bool) 

In [92]: numpy_all_except_one(a) # By default skips last axis 
Out[92]: array([False, False, True], dtype=bool) 

In [93]: a.all(axis=(0,2)) 
Out[93]: array([ True, False, True, True, True, True, True], dtype=bool) 

In [94]: numpy_all_except_one(a, axis=1) 
Out[94]: array([ True, False, True, True, True, True, True], dtype=bool) 

In [95]: a.all(axis=(1,2)) 
Out[95]: array([False, True, True, False, True, True, True], dtype=bool) 

In [96]: numpy_all_except_one(a, axis=0) 
Out[96]: array([False, True, True, False, True, True, True], dtype=bool)