How do you implement boolean indexing in NumPy?
In NumPy, boolean indexing can be used to select elements in an array that satisfy specific conditions. Boolean indexing is a boolean array with the same length as the original array, where each element indicates whether to select the corresponding element.
Here are the steps to select an array using Boolean indexing:
- Create a boolean array with elements either being True or False, indicating whether the corresponding element satisfies the condition.
- Use a boolean array as an index to select elements that meet the condition.
Here is an example demonstrating how to use boolean indexing to select elements in an array that are greater than 5.
import numpy as np
# 创建一个示例数组
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# 创建布尔数组,指示数组中哪些元素大于5
bool_arr = arr > 5
# 使用布尔数组作为索引来选择满足条件的元素
selected_arr = arr[bool_arr]
print(selected_arr)
The output is:
[ 6 7 8 9 10]
In the example above, bool_arr is a boolean array with elements [False, False, False, False, False, True, True, True, True, True]. We then use bool_arr as an index to select elements in arr corresponding to the True positions, allowing us to obtain the elements that meet the condition.