0

This is a generalization of this question.

I want the fastest way to find, for each element of a, all the indexes corresponding to this element in b.

import numpy as np
a = np.array([1, 2, 4])
b = np.array([1, 2, 2, 3, 10, 4, 4, 4])

Here the output would be [[0], [1,2], [5,6,7]]

Valentin Macé
  • 1,150
  • 1
  • 10
  • 25
  • Numpy does not support jagged arrays so I presume you're looking for a list as output. This is not very efficient. Instead you should consider accepting a 3x8 array of booleans. – Reinderien Nov 14 '22 at 21:26
  • `np.in1d` takes different approaches depending on the relative size of `a` and `b`. For relatively small `a` is iterates on it, joining the results with `logical_and`. If they are more equal it uses sorting. The same sort of considerations may apply to your example. While it is easy to get `a[:,None]==b`,, and even `np.nonzero` on that, separating the results into your lists will (most likely) require some sort of iteration on the dimension of `a`. – hpaulj Nov 14 '22 at 21:56
  • Maybe you shouldn't worry about efficiency in iterating on `a`. The only way you'll be able to use the resulting list of lists will a list iteration. – hpaulj Nov 14 '22 at 22:01

0 Answers0