Numpy where function multiple conditions

ghz 3months ago ⋅ 106 views

I have an array of distances called dists. I want to select dists which are within a range.

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

However, this selects only for the condition

 (np.where(dists <= r + dr))

If I do the commands sequentially by using a temporary variable it works fine. Why does the above code not work, and how do I get it to work?

Answers

The issue with your code is that the expression:

(np.where(dists >= r)) and (np.where(dists <= r + dr))

is incorrect because and is a logical operator that evaluates two boolean expressions, rather than combining two conditions element-wise. In NumPy, you need to use element-wise logical operators to apply multiple conditions to an array.

Instead of using and, you should use the element-wise logical & operator. Also, np.where is not necessary for this, as you can directly apply boolean indexing with a logical condition.

Here’s the correct way to apply the two conditions:

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

Explanation:

  • (dists >= r) and (dists <= r + dr) each create a boolean array that is True where the condition is met and False elsewhere.
  • The & operator combines these boolean arrays element-wise.
  • The result is used to index into dists, returning only the elements that satisfy both conditions.

This will select all values in dists that are greater than or equal to r and less than or equal to r + dr.