Python: 如何索引一个numpy数组的元素?

Python: How to index the elements of a numpy array?

我正在寻找一个函数,该函数可以执行函数 indices 在以下假设代码中执行的操作:

indices( numpy.array([[1, 2, 3], [2, 3, 4]]) )

{1: [(0,0)], 2: [(0,1),(1,0)], 3: [(0,2),(1,1)], 4: [(1,2)]}

具体来说,我想生成一个字典,其键是展平数组中的唯一元素,其值是相应键的完整索引的列表。

我查看了 where 函数,但它似乎没有提供解决大型数组问题的有效方法。执行此操作的最佳方法是什么?

注意:我正在使用 Python 2.7

鉴于您想要的输出是一本字典,我认为不会有一种有效的方法来使用 NumPy 操作来执行此操作。你最好的选择可能是

import collections
import itertools

d = collections.defaultdict(list)
for indices in itertools.product(*map(range, a.shape)):
    d[a[indices]].append(indices)

我不知道 numpy,但如果只使用数组,这是一个示例解决方案:

arrs = [[1, 2, 3], [2, 3, 4]]
dict = {}

for i in range(0, len(arrs)):
    arr = arrs[i]
    for j in range(0, len(arr)):
        num = arr[j]
        indices = dict.get(num)
        if indices is None:
            dict[num] = [(i, j)]
        else:
            dict[num].append((i, j))

numpy_indexed 包可以高效且完全矢量化的方式执行此类分组操作,即:

import numpy_indexed as npi
a = np.array([[1, 2, 3], [2, 3, 4]])
keys, values = npi.group_by(a.reshape(-1), np.indices(a.shape).reshape(-1, a.ndim))