在Python/Numpy中同时分配相同的数组索引

6

我希望在Python中找到一种快速的方法(不使用for循环)来分配数组的重复索引。

以下是使用for循环得到的期望结果:

import numpy as np
a=np.arange(9, dtype=np.float64).reshape((3,3))
# The array indices: [2,3,4] are identical.
Px = np.uint64(np.array([0,1,1,1,2]))
Py = np.uint64(np.array([0,0,0,0,0]))
# The array to be added at the array indices (may also contain random numbers).
x = np.array([.1,.1,.1,.1,.1])

for m in np.arange(len(x)):
    a[Px[m]][Py[m]] += x

print a
%[[ 0.1  1.  2.]
%[ 3.3  4.  5.]
%[ 6.1  7.  8.]]

当我尝试在索引位置Px和Pyx添加到a中时,显然得不到相同的结果(3.3 vs. 3.1):

a[Px,Py] += x
print a
%[[ 0.1  1.  2.]
%[ 3.1  4.  5.]
%[ 6.1  7.  8.]]

有没有使用numpy的方法来实现这个?谢谢。

首先,我会将值分组在一起,这样你就有了一个元组列表(Px,Py)。然后对该列表进行排序,计算出现次数,将x乘以该数字并添加到数组中。但是不知何故,numpy似乎跳过了重复的条目...很奇怪。 - Dschoni
1个回答

7

是的,这是可以做到的,但有些棘手:

# convert yourmulti-dim indices to flat indices
flat_idx = np.ravel_multi_index((Px, Py), dims=a.shape)
# extract the unique indices and their position
unique_idx, idx_idx = np.unique(flat_idx, return_inverse=True)
# Aggregate the repeated indices 
deltas = np.bincount(idx_idx, weights=x)
# Sum them to your array
a.flat[unique_idx] += deltas

啊,你比我早了4秒钟给出完全相同的答案。虽然,我真诚地希望有更好的方法来解决这个问题。 - Daniel
谢谢!我喜欢你使用np.ravel_multi_index函数获取平面索引,然后使用带有可选权重参数的np.bincount的方式。 - Paul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接