我有兩個長度相同的陣列(在本例中為 6)。一店floats:
a = np.array([0.2, 0.01, 0.5, 0.7, 0., 0.002])
第二個存盤索引(因此,int值):
indices = np.array([4, 9, 0, 2, 2, 4])
在我的代碼中,我初始化了另一個陣列,它的長度通常與aand不同indices,例如在本例中為 10:
c = np.zeros(10)
我想找到一種 Pythonic 方式來完成以下任務:
for i in range(len(indices)):
c[indices[i]] = a[i]
在這個例子中,它產生:
[0.5 0. 0.7 0. 0.202 0. 0. 0. 0. 0.01 ]
我試著看一下這個精彩的例子,但是我不確定如何在這里應用它。
uj5u.com熱心網友回復:
您可以使用ufunc的.at方法:np.add
np.add.at(c, indices, a)
這是ufuncs方法的頁面help:.at
at(...) method of numpy.ufunc instance
at(a, indices, b=None, /)
Performs unbuffered in place operation on operand 'a' for elements
specified by 'indices'. For addition ufunc, this method is equivalent to
``a[indices] = b``, except that results are accumulated for elements that
are indexed more than once. For example, ``a[[0,0]] = 1`` will only
increment the first element once because of buffering, whereas
``add.at(a, [0,0], 1)`` will increment the first element twice.
.. versionadded:: 1.8.0
Parameters
----------
a : array_like
The array to perform in place operation on.
indices : array_like or tuple
Array like index object or slice object for indexing into first
operand. If first operand has multiple dimensions, indices can be a
tuple of array like index objects or slice objects.
b : array_like
Second operand for ufuncs requiring two operands. Operand must be
broadcastable over first operand after indexing or slicing.
uj5u.com熱心網友回復:
對于sum,您的操作正是bincount:
np.bincount(indices, weights=a)
輸出:
array([0.5 , 0. , 0.7 , 0. , 0.202, 0. , 0. , 0. , 0. , 0.01 ])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/410467.html
標籤:
