2017-04-05 55 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)