-3

So I'm trying to learn Numpy and I cannot understand how this block of code is giving the output it is:

arr = array([1,2,3,4,5,6,7,8,9,10])

arr[arr>5]

Output :

array([6,7,8,9,10])

I do know that actually an array of boolean values is returned by arr>5 but I just can't understand how that boolean array when passed to arr[] gives the specified output. Help Appreciated.

1

1 Answer 1

0
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> a
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

As you already said, a > 5 results in an array of boolean values:

>>> mask = a > 5
>>> mask
array([False, False, False, False, False,  True,  True,  True,  True,
        True])

This can be interpreted as a mask. Similar to the way you can access single elements, for example the first element, with

>>> a[0]
1

You can access specific elements by using index arrays through this mask:

>>> a[mask]
array([ 6,  7,  8,  9, 10])

1, 2, 3, 4, 5 don't appear because the first 5 elements of mask are False. The rest is True and therefore 6, 7, 8, 9, 10 are shown.

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

2 Comments

Ohk! I get it now. Thank you!
Ok. Thank you for informing me. I'll keep that in mind.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.