[Numpy-discussion] Inverted indices

Stéfan van der Walt stefan at sun.ac.za
Thu Aug 7 07:31:12 EDT 2014


Hi Nicolas

On Thu, Aug 7, 2014 at 1:16 PM, Nicolas P. Rougier
<Nicolas.Rougier at inria.fr> wrote:
> Here is a small example:
>
> Z = [(0,0), (1,1), (2,2), (3,3), (4,4))
> I  = [0, 20, 23, 24, 37]
>
> S = [ 20,20,0,24]
> -> Result should be [(1,1), (1,1), (0,0),(3,3)]
>
> S = [15,15]
> -> Wrong (15 not in I) but ideally, I would like this to be converted to [(0,0), (0,0)]

First try:

Z = np.array([(0,0), (1,1), (2,2), (3,3), (4,4)])
I = np.array([0, 20, 23, 24, 37])
S = np.array([ 20,20,0,24,15])

out = np.zeros((len(S), len(Z[0])))
mask = (S[:, np.newaxis] == I)
item, coord = np.where(mask)
out[item, :] = Z[coord]

Perhaps there's a neater way of doing it!

Stéfan



More information about the NumPy-Discussion mailing list