2016-11-18 51 views
0

我想初始化一個只能包含0或1的numpy數組(n,m)。 此外,我想以後到np.bitwise_or與數組。np.ndarray ndarrays上的bitwise_or運算符失敗

例如,如果我嘗試:

import numpy as np 
myArray = np.zeros([4,4]) 
myRow = myArray[1,] 
myCol = myArray[,1] 
np.bitwise_or(myRow, myCol) 

它失敗:

TypeError: ufunc 'bitwise_or' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' 

我怎樣才能做到這一點以類似的方式,但沒有錯誤?

如果我嘗試,

np.bitwise_or([0,0,0,0], [0,0,0,0]) 

它的實際工作。

回答

2

默認情況下,np.zeros將使用float dtype,並且不能在浮點數上執行按位運算。 np.bitwise_or([0,0,0,0], [0,0,0,0])作用於整數,這就是它工作的原因。

如果你的整數關口,而不是D型,當你構建myArray,它會工作太:

In [9]: myArray = np.zeros([4,4], dtype=int) 

In [10]: myRow = myArray[1,:] 

In [11]: myCol = myArray[:,1] 

In [12]: np.bitwise_or(myRow, myCol) 
Out[12]: array([0, 0, 0, 0]) 

,或者我們可以稱之爲astype(int)

In [14]: myArray = np.array([[1.0,0.0,1.0,0.0], [1.0,1.0,1.0,0.0]]) 

In [15]: np.bitwise_or(myArray[0].astype(int), myArray[1].astype(int)) 
Out[15]: array([1, 1, 1, 0]) 

這就是說,如果你知道數組總是隻包含0或1,您應該考慮使用bool陣列:

In [21]: myArray = myArray.astype(bool) 

In [22]: np.bitwise_or(myArray[0], myArray[1]) 
Out[22]: array([ True, True, True, False], dtype=bool) 
相關問題