将数组的值分配给另一个数组的大多数 Pythonic 方式

Most Pythonic way of assigning values of array to another array

我有两个长度相同的数组(在本例中为 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])

在我的代码中,我初始化了另一个数组,它的长度通常不同于 aindices,例如本例中的 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 ]

我试着查看 this brilliant example,但我不确定如何在此处应用它。

对于sum,你的操作正是bincount

np.bincount(indices, weights=a)

输出:

array([0.5  , 0.   , 0.7  , 0.   , 0.202, 0.   , 0.   , 0.   , 0.   ,  0.01 ])

您可以使用 np.add ufunc 的 .at 方法:

np.add.at(c, indices, a)

这是 ufuncs 的 .at 方法的 help 页面:

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.