2
votes

I have a numpy array like this:

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])

And I want to get a list of indexes of the found values by groups

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]

# [...]

The first approach that comes to my mind (that´s not very 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

Which is the most efficient way to achieve this with numpy arrays?

3
Although this is not numpy, combining itertools.groupby and enumerate would work. - user202729
Is arr always sorted? - hpaulj
@hpaulj no, as you can see there is a 9 is in the middle of the array as well. I have added more numbers to avoid the misunderstanding - ChesuCR
There's nothing inherently array-like about this problem - it's really about collecting positions in a list. Your result is lists of varying length which is a good indicator that this doesn't have a fast numpy solution. - hpaulj

3 Answers

2
votes

This should not be too slow. The array is iterated only once. The result (ind) is a dictionary value -> list of indexes.

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
votes

You can use numpy.unique to find all the unique values and numpy.where to find their indexes:

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

Now you have a dictionary of indexes of each value and you can assign what you want to your index_list_* lists.

2
votes

Might not be the fastes but a oneliner with numpy would be:

index_dict = {v: np.flatnonzero(arr == v) for v in np.unique(arr)}