numpy中如何按np.where返回的首数组元素分组次数组并取各分组中心值
实现方案
步骤1:接收np.where返回的匹配结果
首先拿到分组编号数组和对应的位置数组:
import numpy as np a = np.array([[383, 383, 384, 384, 384, 384, 384, 384, 384, 421, 422, 422, 422, 422, 423, 423, 423, 423, 423, 423, 479, 480, 481, 482, 483, 485, 485, 485, 485, 485, 485, 485, 513, 515, 517]]) b = np.array([384, 423, 485]) group_idx, pos_arr = np.where(a == b[:, None])
步骤2:按分组编号聚合位置得到嵌套列表
提供两种实现方式可选:
方式1:numpy原生实现(性能更高,适合大数据量)
利用group_idx同组值连续的特性直接切割:
# 定位分组切割点 split_points = np.where(np.diff(group_idx) != 0)[0] + 1 # 切割位置数组得到分组 grouped = np.split(pos_arr, split_points) # 转换为嵌套列表 grouped_list = [sub.tolist() for sub in grouped]
方式2:Python原生字典实现(逻辑更直观)
from collections import defaultdict group_map = defaultdict(list) for g, pos in zip(group_idx, pos_arr): group_map[g].append(pos) # 按分组编号排序得到最终嵌套列表 grouped_list = [val for key, val in sorted(group_map.items())]
两种方式输出的grouped_list均为:[[2, 3, 4, 5, 6, 7, 8], [14, 15, 16, 17, 18, 19], [25, 26, 27, 28, 29, 30, 31]]
步骤3:计算每个子列表的中心值
根据你对中心值的定义选择对应的实现:
- 数值中位数(偶数长度取两数平均):
centers = [np.median(sub) for sub in grouped] # 输出:[5.0, 16.5, 28.0] - 索引中心(取子列表中间位置的元素,偶数长度默认取中间偏左):
centers = [sub[len(sub)//2] for sub in grouped_list] # 输出:[5, 16, 28]
内容的提问来源于stack exchange,提问作者baronsec
相关产品推荐
相关产品推荐

