Python如何查找numpy数组每行满足条件的元素索引并转换为字典
高效实现方案
下面两种方案都避免了逐行遍历数组调用自定义函数,在大数组场景下性能远高于逐行处理:
方案1:纯NumPy向量化实现(大数组优先选择)
利用np.unique定位行分界点,直接拆分列索引,全程为NumPy底层向量操作,无Python层面循环,处理十万级以上行的数组时性能优势明显:
import numpy as np # 基于你已经得到的g0数组处理 rows, cols = g0.T # 获取所有存在符合条件元素的行号、每行首次出现的索引、每行符合条件的元素个数 unique_rows, split_idx, _ = np.unique(rows, return_index=True, return_counts=True) # 按行分界点拆分列索引数组 col_groups = np.split(cols, split_idx[1:]) # 转换为目标字典格式 res = {row: group.tolist() for row, group in zip(unique_rows, col_groups)} # 可选:如果需要保留无符合条件元素的行(值设为空列表),补充以下代码 for i in range(myarray.shape[0]): res.setdefault(i, [])
输出和你期望的格式完全一致。
方案2:defaultdict遍历实现(小数组更简洁)
直接遍历argwhere返回的坐标对,用collections.defaultdict聚合结果,线性时间复杂度,逻辑更易读,适合小规模数组场景:
from collections import defaultdict res = defaultdict(list) for row, col in g0: res[row].append(col) # 可选:转为普通dict res = dict(res)
内容的提问来源于stack exchange,提问作者Xunny
相关产品推荐
相关产品推荐

