假設我有 2 個一維 numpy 陣列k和d. 我想在 array 的每個元素k和整個 array之間執行一個簡單的計算d。如果沒有 for 回圈,我該怎么做?我想做一個矢量計算。
>>> k = np.array([4.1, 3.2, 1.2, 99.2])
>>> d= np.array([ 0., 2., 4., 8., 14., 100.])
>>>
>>> for kk in k:
... print 6 - (kk >= d).sum()
...
3
4
5
1
>>> 6 - (k >= d).sum()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,) (6,)
也嘗試了以下方法,但沒有奏效
>>> d = np.array([[ 0., 2., 4., 8., 14., 100.], [ 0., 2., 4., 8., 14., 100.], [ 0., 2., 4., 8., 14., 100.], [ 0., 2., 4., 8., 14., 100.]])
>>> k = np.array([4.1, 3.2, 1.2, 99.2])
>>> 6 - (k >= d).sum()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,) (4,6)
>>>
uj5u.com熱心網友回復:
這里的關鍵是用 索引其中一個陣列[:, None]。shape這將為它們添加前綴1,導致陣列的每個專案都被封裝在自己的陣列中。這樣,numpy 將創建一個計算網格:
>>> 6 - (k[:, None] >= d).sum(axis=1)
array([3, 4, 5, 1])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/448410.html
