NumPy: Select indices satisfying multiple conditions in a NumPy array
Select Indices Satisfying Conditions
Write a NumPy program to select indices satisfying multiple conditions in a NumPy array.
Sample array:
a = np.array([97, 101, 105, 111, 117])
b = np.array(['a','e','i','o','u'])
Note: Select the elements from the second array corresponding to elements in the first array that are greater than 100 and less than 110
Pictorial Presentation:

Sample Solution:
Python Code:
Sample Output:
Original arrays [ 97 101 105 111 117] ['a' 'e' 'i' 'o' 'u'] Elements from the second array corresponding to elements in the first array that are greater than 100 and less than 110: ['e' 'i']
Explanation:
In the above exercise –
- a = np.array(...): Create a NumPy array 'a' containing integer values.
- b = np.array(...): Create a NumPy array 'b' containing string values. The arrays 'a' and 'b' have the same length.
- (100 < a): This part creates a boolean array with the same shape as 'a', where each element is True if the corresponding element in 'a' is greater than 100, and False otherwise.
- (a < 110): This part creates a boolean array with the same shape as 'a', where each element is True if the corresponding element in 'a' is less than 110, and False otherwise.
- (100 < a) & (a < 110): Use the & operator to perform element-wise logical AND between the two boolean arrays created in steps 3 and 4. The resulting boolean array has True values where the corresponding elements in 'a' are both greater than 100 and less than 110, and False values otherwise.
- b[(100 < a) & (a < 110)]: Use boolean indexing to select elements from array 'b' where the corresponding elements in array 'a' satisfy the condition (greater than 100 and less than 110).
- print(...): Finally print the resulting array.
For more Practice: Solve these Related Problems:
- Write a NumPy program to select indices of an array that satisfy multiple conditions using np.where and logical operators.
- Create a function that returns indices for elements meeting a specified range of criteria and validates the results.
- Test selection of indices on arrays with overlapping conditions and verify the output using boolean masks.
- Implement a solution that filters one array based on conditions applied to another and returns the corresponding indices.
Go to:
PREV : Remove Rows with Non-Numeric Values
NEXT : Find Magnitude of Vector
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.