0

I want to get hold of the positions in an array and want to extract the values in those positions from another array. I have two arrays:

Array_1 = (1, 0, 23, 4, 0, 0, 17, 81, 0, 10)
Array_2 = (11, 12, 13, 14, 15, 16, 17, 18, 19, 20)

With

a, b = numpy.unique(Array_1)

I get the following: a contains the values and b the positions.

a = (1, 23, 4, 17, 81, 10)
b = (0, 2, 3, 6, 7, 9)

I want the values of Array_2 at the positions of Array_1. In other words, I want:

c = (11, 13, 14, 17, 18, 20)

How do I get hold of those values?

1
  • There are multiple flaws in your example. 1st) numpy.unique will return a sorted array of unique values, including the 0. 2nd) To get the indices of np.unique, you have to use the keyword return_index=True. Commented Aug 27, 2015 at 9:29

1 Answer 1

3

Numpy supports vectorized indexing, see "Integer array indexing". In practice, this means you can do:

a, b = numpy.unique(Array_1, return_index=True)
c = Array_2[b]
Sign up to request clarification or add additional context in comments.

4 Comments

You sure this works? It gives me array([12, 11, 14, 20, 17, 13, 18]), unless I am doing something wrong at my end.
@Divakar, I was going by the text in the question, but now I see that the example values in there are weird. In the OP a isn't sorted and doesn't include 0. That's why the order in my answer's output is different and includes 12.
It is weird indeed. It seems one can get the output with just Array_2[Array_1!=0] too. Not sure what's the significance of numpy.unique.
np.unique returns all unique values of an array, therefore every value is present only once. Array_2[Array_1!=0] will evaluate at *all* non-zero values in Array_1, which is something entirely different. BTW: To do this sort of slicing, one would need to convert the tuples to np.ndarray` first...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.