如何使用numpy数组有效地获取特定值选择的索引列表?

时间:2018-02-08 13:15:06

标签: python python-3.x numpy

我有一个像这样的numpy数组:

import numpy as np
arr = np.array([9, 6, 3, 8, 2, 3, 3, 4, 4, 9, 5, 6, 6, 6, 6, 7, 8, 9])

我希望按组

获取找到的值的索引列表
index_list_2 = [4 ]         # index list of the element with the value 2
index_list_3 = [2, 5, 6 ]
index_list_4 = [7, 8 ]
index_list_9 = [0, 9, 17]

# [...]

我想到的第一种方法(不是非常pythonic):

i = 0
for x in arr:
    if x == 2:
        index_list_2 += [i]
    if x == 3:
        index_list_3 += [i]
    if x == 4:
        index_list_4 += [i]
    if x == 9:
        index_list_9 += [i]
    i += 1

使用numpy数组实现此目的的最有效方法是什么?

3 个答案:

答案 0 :(得分:2)

您可以使用numpy.unique查找所有唯一值,并使用numpy.where查找其索引:

import numpy as np
arr = np.array([2, 3, 3, 4, 4, 9, 5, 6, 6, 6, 6, 7, 8, 9])

# get the unique values
unique_arr = np.unique(arr)

# loop through the unique numbers and find the indeces
indexes_value = {}
for num in unique_arr:
    indexes = np.where(arr == num)[0]
    indexes_value[num] = indexes  # or list(indexes) if you prefer

现在您有一个每个值的索引字典,您可以将所需内容分配给index_list_*列表。

答案 1 :(得分:2)

这不应该太慢。该数组只迭代一次。 结果(ind)是字典值 - >索引列表。

import numpy as np
arr = np.array([2, 3, 3, 4, 4, 9, 5, 6, 6, 6, 6, 7, 8, 9])

ind = dict()
for i, val in enumerate(arr):
  ind.setdefault(val, []).append(i)

答案 2 :(得分:2)

可能不是吝啬但是有numpy的oneliner会是:

data = data / data.max() #normalizes data in range 0 - 255
data = 255 * data
img = data.astype(np.uint8)
相关问题