NumPy - Filtering rows by multiple conditions

NumPy - Filtering rows by multiple conditions

In NumPy, you can filter rows of a 2D array based on multiple conditions using boolean indexing. Let's see how to filter rows by multiple conditions with some examples.

Assuming you have a 2D array data:

import numpy as np data = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ]) 

1. Filtering with a single condition:

To filter rows where the first column's value is greater than 5:

filtered_data = data[data[:, 0] > 5] print(filtered_data) 

Output:

[[ 7 8 9] [10 11 12]] 

2. Filtering with multiple conditions:

To filter rows where the first column's value is greater than 5 and the second column's value is less than 11:

  • Use & for the logical AND operation.
  • Ensure each condition is enclosed in parentheses.
filtered_data = data[(data[:, 0] > 5) & (data[:, 1] < 11)] print(filtered_data) 

Output:

[[7 8 9]] 

3. Using OR operation:

To filter rows where the first column's value is less than 4 or the third column's value is greater than 9:

  • Use | for the logical OR operation.
filtered_data = data[(data[:, 0] < 4) | (data[:, 2] > 9)] print(filtered_data) 

Output:

[[ 1 2 3] [10 11 12]] 

4. Using NOT operation:

To filter rows where the first column's value is not 4:

  • Use ~ for the logical NOT operation.
filtered_data = data[~(data[:, 0] == 4)] print(filtered_data) 

Output:

[[ 1 2 3] [ 7 8 9] [10 11 12]] 

In summary, boolean indexing in NumPy is a powerful tool that allows you to filter data based on multiple conditions. Just remember to enclose each condition in parentheses when combining them with logical operations like &, |, and ~.


More Tags

web-frontend quotation-marks grand-central-dispatch ssl variable-assignment windows-container bigdecimal presentviewcontroller new-window mesh

More Programming Guides

Other Guides

More Programming Examples