After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.

Intuitively, np.where is like asking "tell me where in this array, entries satisfy a given condition".

>>> a = np.arange(5,10)
>>> np.where(a < 8)       # tell me where in a, entries are < 8
(array([0, 1, 2]),)       # answer: entries indexed by 0, 1, 2

It can also be used to get entries in array that satisfy the condition:

>>> a[np.where(a < 8)] 
array([5, 6, 7])          # selects from a entries 0, 1, 2

When a is a 2d array, np.where() returns an array of row idx's, and an array of col idx's:

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

As in the 1d case, we can use np.where() to get entries in the 2d array that satisfy the condition:

>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2

array([9])


Note, when a is 1d, np.where() still returns an array of row idx's and an array of col idx's, but columns are of length 1, so latter is empty array.

Answer from Alex Dalyac on Stack Overflow
🌐
NumPy
numpy.org › doc › 2.5 › reference › generated › numpy.where.html
numpy.where — NumPy v2.5 Manual
numpy.where(condition, [x, y, ]/)# Return elements chosen from x or y depending on condition. Note · When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses.
🌐
GeeksforGeeks
geeksforgeeks.org › numpy › numpy-where-in-python
numpy.where() in Python - GeeksforGeeks
September 30, 2025 - With x and y: returns a new array choosing from x where True, y where False (supports broadcasting and dtype rules). In this example, numpy.where() checks where the condition arr % 2 == 0 is true and returns the indices.
🌐
DataCamp
datacamp.com › doc › numpy › where
NumPy where()
The `where()` function in NumPy is used for array computation and analysis; it returns elements chosen from `x` or `y` depending on `condition`, or the indices of elements that meet the condition when only `condition` is provided.
🌐
NumPy
numpy.org › doc › 2.4 › reference › generated › numpy.where.html
numpy.where — NumPy v2.4 Manual
numpy.where(condition, [x, y, ]/)# Return elements chosen from x or y depending on condition. Note · When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it behaves correctly for subclasses.
🌐
Machine Learning Plus
machinelearningplus.com › blog › how to use numpy where function?
How to Use Numpy Where Function? - machinelearningplus
January 26, 2023 - ... The numpy.where() function takes in the condition as one of the required arguments and returns the indices array for elements which satisfy the given condition. Condition is nothing but an expression involving usage of operators with the ...
🌐
Medium
medium.com › @heyamit10 › understanding-numpy-where-with-two-conditions-21871ed01aa6
Understanding numpy.where() with Two Conditions | by Hey Amit | Medium
March 6, 2025 - Think of numpy.where() as a decision-maker for your arrays. It checks a condition, and based on whether it’s True or False, it picks a value for you.
Find elsewhere
Top answer
1 of 9
316

The best way in your particular case would just be to change your two criteria to one criterion:

dists[abs(dists - r - dr/2.) <= dr/2.]

It only creates one boolean array, and in my opinion is easier to read because it says, is dist within a dr or r? (Though I'd redefine r to be the center of your region of interest instead of the beginning, so r = r + dr/2.) But that doesn't answer your question.


The answer to your question:
You don't actually need where if you're just trying to filter out the elements of dists that don't fit your criteria:

dists[(dists >= r) & (dists <= r+dr)]

Because the & will give you an elementwise and (the parentheses are necessary).

Or, if you do want to use where for some reason, you can do:

 dists[(np.where((dists >= r) & (dists <= r + dr)))]

Why:
The reason it doesn't work is because np.where returns a list of indices, not a boolean array. You're trying to get and between two lists of numbers, which of course doesn't have the True/False values that you expect. If a and b are both True values, then a and b returns b. So saying something like [0,1,2] and [2,3,4] will just give you [2,3,4]. Here it is in action:

In [230]: dists = np.arange(0,10,.5)
In [231]: r = 5
In [232]: dr = 1

In [233]: np.where(dists >= r)
Out[233]: (array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]),)

In [234]: np.where(dists <= r+dr)
Out[234]: (array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]),)

In [235]: np.where(dists >= r) and np.where(dists <= r+dr)
Out[235]: (array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]),)

What you were expecting to compare was simply the boolean array, for example

In [236]: dists >= r
Out[236]: 
array([False, False, False, False, False, False, False, False, False,
       False,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True], dtype=bool)

In [237]: dists <= r + dr
Out[237]: 
array([ True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True, False, False, False, False, False,
       False, False], dtype=bool)

In [238]: (dists >= r) & (dists <= r + dr)
Out[238]: 
array([False, False, False, False, False, False, False, False, False,
       False,  True,  True,  True, False, False, False, False, False,
       False, False], dtype=bool)

Now you can call np.where on the combined boolean array:

In [239]: np.where((dists >= r) & (dists <= r + dr))
Out[239]: (array([10, 11, 12]),)

In [240]: dists[np.where((dists >= r) & (dists <= r + dr))]
Out[240]: array([ 5. ,  5.5,  6. ])

Or simply index the original array with the boolean array using fancy indexing

In [241]: dists[(dists >= r) & (dists <= r + dr)]
Out[241]: array([ 5. ,  5.5,  6. ])
2 of 9
96

The accepted answer explained the problem well enough. However, the more Numpythonic approach for applying multiple conditions is to use numpy logical functions. In this case, you can use np.logical_and:

np.where(np.logical_and(np.greater_equal(dists,r),np.greater_equal(dists,r + dr)))
🌐
NumPy
numpy.org › doc › 2.5 › reference › generated › numpy.argwhere.html
numpy.argwhere — NumPy v2.5 Manual
numpy.argwhere(a)[source]# Find the indices of array elements that are non-zero, grouped by element. Parameters: aarray_like · Input data. Returns: index_array(N, a.ndim) ndarray · Indices of elements that are non-zero. Indices are grouped by element. This array will have shape (N, a.ndim) where N is the number of non-zero items.
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.argwhere.html
numpy.argwhere — NumPy v2.6.dev0 Manual
numpy.argwhere(a)[source]# Find the indices of array elements that are non-zero, grouped by element. Parameters: aarray_like · Input data. Returns: index_array(N, a.ndim) ndarray · Indices of elements that are non-zero. Indices are grouped by element. This array will have shape (N, a.ndim) where N is the number of non-zero items.
🌐
StrataScratch
stratascratch.com › blog › exploring-numpy-where-in-python
Exploring NumPy where() in Python for Conditional Operations - StrataScratch
September 17, 2025 - In this case, chaining and combining conditions with np.where() would be a good choice. Logical operators like & (and), | (or), and ~ (not) with parentheses can let you make your own logic. We'll use scores to expand on our previous example. Mark a score as "Medium" if it falls between 50 and 80. ... Let’s see the code. import numpy as np scores = np.array([[45, 82, 60], [30, 55, 90]]) labels = np.where(scores >= 80, 'High', np.where((scores >= 50) & (scores < 80), 'Medium', 'Low')) print(labels)
🌐
AskPython
askpython.com › python-modules › numpy › python-numpy-where
np.where in Python: Find Indices and Replace Values with numpy.where() - AskPython
1 week ago - That shape catches you on the first line you print, and the trailing comma inside the parentheses is the clue to why. With numpy.where(), a missing reading can become zero if you choose the wrong fallback, so keep the condition separate from the replacement policy.
🌐
Medium
medium.com › @kelvinsang97 › python-np-where-97bdbdcf9eab
Python np.where(). This function can be used to select… | by Kelvin Kipsang | Medium
February 9, 2023 - Python np.where() This function can be used to select elements from arrays depending on a condition. This choose elements from an array X if the condition holds , otherwise, it will choose from …
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.ma.where.html
numpy.ma.where — NumPy v2.1 Manual
An masked array with masked elements where the condition is masked, elements from x where condition is True, and elements from y elsewhere. ... Equivalent function in the top-level NumPy module.
🌐
Reddit
reddit.com › r/learnpython › how does np.where() work?
r/learnpython on Reddit: How does np.where() work?
March 31, 2022 -

My understanding of np.where() was so far as sort of an arg container for .loc. However in the example below, .loc works, but not when np.where is used as arg. Why is that happening?

df=pd.DataFrame({'Name':['Tom', 'Mia', 'Sam'], 'Age':[15, 26, 32]}, index=['A','B','C'])

print(df.loc[(df['Age']>28)&(df['Name'].str.startswith('S')])

k=np.where((df['Age']>28)&(df['Name'].str.startswith('S'))

print(df.loc[k])

🌐
W3Schools
w3schools.com › python › numpy › numpy_intro.asp
Introduction to NumPy
Data Science: is a branch of computer science where we study how to store, use and analyze data for deriving information from it. NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access and manipulate ...
🌐
Programiz
programiz.com › python-programming › numpy › methods › where
NumPy where()
The NumPy where() method finds indices that are true in an array based on a given condition. The numpy.where() method returns a new array based on a condition applied to each element of an array.
🌐
Medium
medium.com › @whyamit404 › what-is-numpy-where-and-how-does-it-work-acd87afb1141
What is numpy.where and How Does it Work? | by whyamit404 | Medium
February 26, 2025 - In Python, the numpy.where function is your tool for making similar decisions within arrays.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-numpy-where
How to use Python numpy.where() Method | DigitalOcean
Leverage NumPy’s where() function to efficiently select elements from arrays based on conditions, creating new arrays with tailored values.
🌐
YouTube
youtube.com › watch
Use numpy.where() For If Else Conditionals on Python Arrays - YouTube
The numpy.where function is a very powerful way to scale conditional operations to large arrays while reducing computational overhead. Basically, it's a fast...
Published: December 7, 2021