0

I have an array x :

numpy.random.seed(1)
#input
x = numpy.arange(0.,20.,1)
x = x.reshape(5,4)
print(x)

[[ 0.  1.  2.  3.]
 [ 4.  5.  6.  7.]
 [ 8.  9. 10. 11.]
 [12. 13. 14. 15.]
 [16. 17. 18. 19.]]

I want to access the maximum element in this array. In my assignment, the answer has this line to access the maximum one in x :

print(x[x==x.max()])
[19.]

I search documentation but found only one way of accessing the maximum element using argmax. I don't find the way of using "==" in the documentation, so I don't understand how this works. Can anyone explain why this works and show where it is in the documentation?

2 Answers 2

2

This is called Boolean array indexing.

With x == x.max(), the below boolean array is generated:

[[ False  False  False  False]
 [ False  False  False  False]
 [ False  False  False  False]
 [ False  False  False  False]
 [ False  False  False  True]]

Then with x[x==x.max()], the above array is used as a mask to filter the elements of x that correspond to the True.

Reference:

https://numpy.org/devdocs/reference/arrays.indexing.html#boolean-array-indexing

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

Comments

2

This is using a boolean mask array. Here's the documentation.

What you're doing is you're producing a boolean array, then using that as a mask to index into your original array:

# x == x.max()
[[ False  False  False  False]
 [ False  False  False  False]
 [ False  False  False  False]
 [ False  False  False  False]
 [ False  False  False  True]]

1 Comment

@user14416085 Here is another relevant piece of documentation: numpy.org/doc/stable/reference/… Your original code is basically saying "Create an array with all the elements in the original array that are equal to the maximum element in the original array".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.