如何在NumPy ndarray中忽略0并查找每行Top-K元素的索引
NumPy数组每行排除0值后取Top-K元素索引的实现
问题场景
给定如下NumPy数组:
import numpy as np x = np.array([[4.,0.,2.,0.,8.], [1.,3.,0.,9.,5.], [0.,0.,4.,0.,1.]])
需要实现:对每行排除0值后,提取Top-K(示例k=3)元素的索引;若该行正元素数量不足k个,则返回所有正元素的索引(按元素从大到小排序后的对应索引)。
解决方案
核心思路是先筛选每行的非0元素索引,再对非0值降序排序,最后截取对应索引的前k个(或全部)。
方式1:得到数组列表形式结果
k = 3 result = [] for row in x: # 获取当前行非0元素的索引 non_zero_indices = np.where(row != 0)[0] # 获取对应非0元素的值 non_zero_values = row[non_zero_indices] # 对非0值降序排序,得到排序后的位置索引 sorted_positions = np.argsort(-non_zero_values) # 提取排序后的原索引,取前k个(不足k则取全部) top_k_indices = non_zero_indices[sorted_positions][:k] result.append(top_k_indices.tolist()) print(result) # 输出:[[4, 0, 2], [3, 4, 1], [2, 4]]
方式2:得到扁平化数组形式结果
只需将上述代码中的append改为extend即可:
k = 3 flat_result = [] for row in x: non_zero_indices = np.where(row != 0)[0] non_zero_values = row[non_zero_indices] sorted_positions = np.argsort(-non_zero_values) top_k_indices = non_zero_indices[sorted_positions][:k] flat_result.extend(top_k_indices.tolist()) print(flat_result) # 输出:[4, 0, 2, 3, 4, 1, 2, 4]
关键步骤说明
np.where(row != 0)[0]:精准筛选出当前行所有非0元素的原始索引np.argsort(-non_zero_values):通过对值取负后排序,实现对非0元素的降序排序,返回的是排序后元素在非0数组中的位置non_zero_indices[sorted_positions]:将排序后的位置映射回原始索引,得到按值从大到小排列的索引列表[:k]:自动处理元素数量不足k的情况,直接返回所有非0元素的索引
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

