aamer aamer - 1 year ago 61

Python Question

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.

Answer Source

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]]`