如何根据布尔数组的True索引范围切片目标数组?
解决方案
要从布尔数组a中提取连续True的区间,并用这些区间切片数组b,可以用NumPy的数组操作快速实现,以下是两种可行方法:
方法一:利用差分找区间边界
这种方法效率较高,适合处理大规模数组:
import numpy as np # 初始化示例数组a和b a = np.zeros(100, dtype=bool) a[10:20] = True a[40:60] = True b = np.arange(100) # 替换成你的实际数组b # 扩展数组以处理边界情况 extended_a = np.concatenate([[False], a, [False]]) # 计算差分,捕捉True区间的起始和结束点 changes = np.diff(extended_a.astype(int)) starts = np.where(changes == 1)[0] ends = np.where(changes == -1)[0] # 生成b的子数组列表 subarrays = [b[start:end] for start, end in zip(starts, ends)]
逻辑说明:
- 在
a前后补False,确保数组开头或结尾就是True时,也能正确识别区间边界 - 将布尔值转为整数后做差分,
1对应从False到True的起始点,-1对应从True到False的结束点 - 配对起始和结束索引,直接切片
b得到对应子数组
方法二:从True索引分组
这种方法逻辑更直观,适合理解:
import numpy as np a = np.zeros(100, dtype=bool) a[10:20] = True a[40:60] = True b = np.arange(100) true_indices = np.where(a)[0] subarrays = [] if len(true_indices) > 0: # 找到索引中断的位置(间隔大于1) split_positions = np.where(np.diff(true_indices) > 1)[0] + 1 # 拆分连续的True索引为多个组 index_groups = np.split(true_indices, split_positions) # 每个组对应b的一个子数组(注意切片是左闭右开,所以结束索引要+1) subarrays = [b[group[0]:group[-1]+1] for group in index_groups]
逻辑说明:
- 先获取所有
True的索引位置 - 通过判断索引间的差值,拆分出连续的索引组
- 每个索引组的首尾对应
b的切片范围,注意切片结束要+1以匹配左闭右开的规则
两种方法最终都会得到[b[10:20], b[40:60]]这样的子数组列表,可根据你的数组规模和可读性需求选择。
内容的提问来源于stack exchange,提问作者Baz
相关产品推荐
相关产品推荐

