Invariance
Invariance

Reputation: 313

Why is numpy.where giving me this output?

I am following the documentation page of numpy.where and found the following code:

>>>x = np.arange(9.).reshape(3, 3)
>>>x
array([[ 0.,  1.,  2.],
   [ 3.,  4.,  5.],
   [ 6.,  7.,  8.]])
>>>np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2])) 

I don't understand why np.where( x > 5 ) gives the output mentioned. I am sorry if this has been asked before but I didn't find any relevant question. Please help.

Upvotes: 0

Views: 31

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117856

numpy.where returns the indices where your condition was True. So in your example x > 5 is True at the following indices

  [(2,0), (2,1), (2,2)]
#  ^6.    ^7.    ^8.

This can be useful if you want to extract those elements from the original array, e.g.

>>> x[np.where( x > 5 )]
array([6., 7., 8.])

Upvotes: 1

Related Questions