How to filter rows that meet certain criteria in numpy?
We can use boolean indexing in numpy to filter rows that meet certain conditions.
Boolean indexing is a method of selecting elements in an array using a boolean array. By creating a boolean array to specify filtering criteria, we can then index the original array to retrieve rows that meet those criteria.
Here is an example:
import numpy as np
# 创建一个示例数组
arr = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 创建一个布尔数组,指定筛选条件
condition = arr > 5
# 使用布尔索引来筛选符合条件的行
filtered_arr = arr[condition]
print(filtered_arr)
The output result is:
[6 7 8 9]
In the example above, we created a two-dimensional array called arr and a boolean array called condition to specify the filtering condition, which is elements in arr greater than 5. We then used boolean indexing arr[condition] to obtain the elements that meet the condition and saved them in filtered_arr. Finally, we printed filtered_arr, which is the rows that meet the condition.