布尔索引 boolean indexing 定义
布尔索引是一种通过使用布尔值(True或False)数组来选择数组中的元素的方法。布尔数组的长度必须与源数组相同,它指示了哪些元素应该被选择或过滤。
通过使用布尔索引,我们可以根据指定条件来选择数组中的元素,这些条件可以是基于元素值的比较、逻辑运算符的组合或其他布尔表达式。
简单来将, 布尔索引就是让 1个 boolean dtype 的adarray 作为另1个adarry 的 filter, 所以 布尔索引更应该是个filter 而不是 index。
语法:
arr_a[arr_b] 其中 arr_a 和 arr_b 都是ndarray 对象, 而且arr_b.dtype 是 bool
"""
introduce of ndarray boolean index:
1. ndarray[bool_array] # means select the elements where bool_array is True
2. bool_array could be a boolean ndarray or a list of boolean values
3. bool_array should have the same length with the ndarray
4. bool_array could be generated by comparison operators e.g. >, <, ==, !=
5. bool_array could be generated by logical operators e.g. &, |, ~
6. bool_array could be generated by np.logical_and, np.logical_or, np.logical_not
7. bool_array could be generated by np.all, np.any
"""
1维数组的 boolean indexing
举个例子:
arr = np.arange(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
logger.info(f"arr: {
arr}") # [0 1 2 3 4 5 6 7 8 9]
arr_filter = [True, False, True, False, True, False, True, False, True, False]
logger.info(f"arr[arr_filter]: {
arr[arr_filter]}") # [0 2 4 6 8]
arr_filter = [True, False, True, False, True, False, True, False, True, False, True]
# logger.info(f"arr[arr_filter]: {arr[arr_filter]}") # error, because the length of arr_filter is not the same as arr
上面例子中, 首先创建了1个1维数组 arr, dtype = int32
然后构建了另1个 1维数组arr_filter , dtype = bool ,
然后利用 arr[arr_filter] 就可以返回另 一个 adarray 对象, 新的对象只包含了 符合 arr_filter 的元素。
在这个例子中, 就得到了1个偶数的子数组 [0, 2, 4, 6, 8]
值得注意的是, arr_filter 的shape 必须与 arr 一致, 才能另到True/false 和 arr的元素一一对应, 否则会出错
更优雅地编写arr_filter
上的arr_filter 是暴力定义的, 显然不符合实际场景
其实如果有1个公式的, 例如上面例子是求偶数, 是可以有其他方法来定义的.
- 直接利用源arr 名字套用公式
arr = np.arange(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
logger.info(f"arr: {
arr}") # [0 1 2 3 4 5 6 7 8 9]
arr_filter = arr % 2 == 0
logger.info(f"arr_filter: