You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将数组中重复值(从第二个起)置零并提取非零元素索引?

数组去重置零及有效索引提取方案

步骤1:将重复值的第二个及之后元素置零

使用NumPy的np.unique方法获取每个值首次出现的索引,再通过全零数组赋值实现需求:

import numpy as np

# 原数组
arr = np.array([0, 50, 50, 50, 150, 150, 150, 150])

# 获取唯一值及其首次出现的索引
unique_values, first_occurrence_indices = np.unique(arr, return_index=True)

# 初始化全零数组
processed_arr = np.zeros_like(arr)

# 仅保留每个值首次出现的元素
processed_arr[first_occurrence_indices] = arr[first_occurrence_indices]

执行后processed_arr结果为:array([ 0, 50, 0, 0, 150, 0, 0, 0])

步骤2:提取值大于0的元素列索引

利用np.where筛选出符合条件的索引:

# 提取大于0的元素索引
arr2 = np.where(processed_arr > 0)[0]

执行后arr2结果为:array([1, 4])

内容的提问来源于stack exchange,提问作者Agustin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 23:22:02