【问题标题】:Most Pythonic way of assigning values of array to another array将数组的值分配给另一个数组的大多数 Pythonic 方式
【发布时间】:2022-01-13 17:06:00
【问题描述】:

我有两个长度相同的数组(在本例中为 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,但我不确定如何在此处应用。

【问题讨论】:

  • indices = np.array([4, **9**, 0, 2, 2, 4]) ... a 没有十项。
  • @wwii 仔细看,它是 a[i],不是 a[indices[i]],请查看我的答案,numpy ufuncs 为这个确切的用例提供了一些东西,.at 方法

标签: python numpy for-loop unique


【解决方案1】:

可以使用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.

【讨论】:

    【解决方案2】:

    对于sum,您的操作正是bincount 的样子:

    np.bincount(indices, weights=a)
    

    输出:

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

    【讨论】:

    • 需要minlength,但应该对总和有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多