我正在閱讀有關向量化表達式的備忘單。要提及的如下numpy array向量化版本
矢量化表達式
np.where(COND中,x,y)是表達的向量化版本 '×如果其他條件Y'
例如:
np.where([True, False], [1, 2], [2, 3]) => ndarray (1, 3)
我不能理解上面的例子。我的理解是我們應該有表達,但是這裏我們列出了[True,False]。
請求在分手解釋以及如何得到ndarray的輸出(1,3)
由於
我正在閱讀有關向量化表達式的備忘單。要提及的如下numpy array向量化版本
矢量化表達式
np.where(COND中,x,y)是表達的向量化版本 '×如果其他條件Y'
例如:
np.where([True, False], [1, 2], [2, 3]) => ndarray (1, 3)
我不能理解上面的例子。我的理解是我們應該有表達,但是這裏我們列出了[True,False]。
請求在分手解釋以及如何得到ndarray的輸出(1,3)
由於
我通常使用np.where
到布爾數組轉換爲索引陣列。考慮下面這個例子:
In [12]: a = np.random.rand((10))
In [13]: a
Out[13]:
array([ 0.80785098, 0.49922039, 0.02018482, 0.69514821, 0.87127179,
0.23235574, 0.73199572, 0.79935066, 0.46667908, 0.11330817])
In [14]: bool_array = a > 0.5
In [15]: bool_array
Out[15]: array([ True, False, False, True, True, False, True, True, False, False], dtype=bool)
In [16]: np.where(bool_array)
Out[16]: (array([0, 3, 4, 6, 7]),)
你的例子說明。對於cond
中的每個值:如果True
,則從x
中挑選值,否則從y
中挑選值。
cond: [True, False]
x : [1, 2]
y : [2, 3]
Result:
cond[0] == True -> out[0] == x[0]
cond[1] == False -> out[1] == y[1]
out == [1, 3]
陣列[True, False]
是什麼會由表達式等x<y
其中x=np.array([1,1])
和y=np.array([2,0])
來製造。所以cond
是一個布爾數組,通常是像前一個表達式的結果。 的一個更真實的上下的用法的示例將是therfore:
np.where(x<y, [1, 2], [2, 3])
您是否閱讀過官方文檔:https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html?你對哪個具體的部分堅持解釋? – Divakar
我的問題是我們如何去輸出ndarray(1,3)在上面的例子 – venkysmarty
可能重複[應用功能蒙面numpy數組](https://stackoverflow.com/questions/36421913/)。還有一個:https://stackoverflow.com/questions/35188508 – Divakar