Python Forum
The where function in numpy
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The where function in numpy
#6
Sometimes, StackOverflow/Google is a better place to look for information :P  
http://stackoverflow.com/a/5642525 Wrote:
Quote:How do they achieve internally that you are able to pass something like x > 5 into a method?
The short answer is that they don't.

Any sort of logical operation on a numpy array returns a boolean array. (i.e. __gt__, __lt__, etc all return boolean arrays where the given condition is true).

E.g.

x = np.arange(9).reshape(3,3)
print x > 5
yields:

Output:
array([[False, False, False],       [False, False, False],       [ True,  True,  True]], dtype=bool)
This is the same reason why something like if x > 5: raises a ValueError if x is a numpy array. It's an array of True/False values, not a single value.

Furthermore, numpy arrays can be indexed by boolean arrays. E.g. x[x>5] yields [6 7 8], in this case.

Honestly, it's fairly rare that you actually need numpy.where but it just returns the indicies where a boolean array is True. Usually you can do what you need with simple boolean indexing.
Reply


Messages In This Thread
The where function in numpy - by saund1pe - Nov-15-2016, 04:57 PM
RE: The where function in numpy - by Larz60+ - Nov-15-2016, 05:08 PM
RE: The where function in numpy - by saund1pe - Nov-15-2016, 05:13 PM
RE: The where function in numpy - by Larz60+ - Nov-15-2016, 06:01 PM
RE: The where function in numpy - by saund1pe - Nov-16-2016, 06:44 PM
RE: The where function in numpy - by nilamo - Nov-16-2016, 08:04 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Need help with NumPy Histogram function coding Triikey 1 927 May-15-2023, 01:45 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020