Numpy: Is there a way to create an array from a sequence of mappings without an outer loop?

For me, this sounds like a normal use case, but I have not yet been able to find the desired function / stream.

I have two numpy arrays, one is a sequence of triplets, and the other is a related sequence of indices. I want to create a 1-dimensional array of equal sequence length, consisting of display elements according to their index.

Example:

mapping = np.array(((25, 120, 240), (18, 177, 240), (0, 0, 0), (10, 120, 285)))
indices = np.array((0, 1, 0, 0))

print "mapping:", mapping
print "indices:", indices
print "mapped:", mapping[indices]

Which produces the following output:

mapping: [[ 25 120 240]
 [ 18 177 240]
 [  0   0   0]
 [  10 120 285]]
indices: [0 1 0 0]
mapped: [[ 25 120 240]
 [ 18 177 240]
 [ 25 120 240]
 [ 25 120 240]]

Of course, this approach takes the entire map array as a single map, and not as a list of maps that return only the 1st or 2nd internal maps in accordance with the index array. But I was looking for this:

mapped: [25 177 0 10]

... which is made of the 1st element of the 1st mapping, the second second mapping and the first of the 3rd and 4th mappings.

numpy, ?

+4
1

, numpy .

In [17]: mapping[(np.arange(indices.shape[-1]),indices)]
Out[17]: array([ 25, 177,   0,   10])

(np.arange), , .

+2

Source: https://habr.com/ru/post/1693811/


All Articles