2

I have got the following python expression in my code

import numpy as np  
a = np.array([1,0,1,0])  
b = np.array([True,False,False,True])
print a[b],b[a]  

The output i am getting looks like this:

[1 0] [False  True False  True]

I am not able to understand how this output is generated.
Can anybody explain it.

1
  • I would suggest you learn the basics of numpy. After that, you will figure out the answer to this problem. Commented Nov 20, 2016 at 14:32

1 Answer 1

5

They are two difference cases

a[b] is logical indexing. The index b must be a boolean array, the same size as a. Each boolean value of b mean take/leave this element of a. That is: for each pair of values in a_i, b_i in vectors a, b: If b_i == True, add a_i to the output vector, otherwise ignore it.

b[a] is indexing with multiple values. Just like in normal python you can do b[0] to take the first value of b, in numpy you can use an array as index, to take multiple elements. in your case, this produces the same result as [b[1], b[0], b[1], b[0]]

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. I got the second case, but a[b] still demands some explanation. I didn't understand the meaning of your statement: 'Each boolean value of b mean take/leave this element of a'.
Yes got it. Thanks for the explanation. Because i am new, u will have to wait for the upvote i already have done for ur answer. It needs me to have some more reputations to do that. So, jus wait. Ur upvote to my question may help me gain some more reputations. Thanks :)

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.