gpt4 book ai didi

python - 将数组的值分配给另一个数组的最 Pythonic 方式

转载 作者:行者123 更新时间:2023-12-02 01:47:44 31 4
gpt4 key购买 nike

我有两个长度相同的数组(在本例中为 6)。一间商店 float :

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 ,但是我不确定如何在这里应用它。

最佳答案

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

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

这是 ufuncs 的 .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.

关于python - 将数组的值分配给另一个数组的最 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70700418/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com