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

如何用Python NumPy无需循环删除数组中满足条件的相似值?

无需for循环删除数组中相似值的方法

可以利用NumPy的**diff()和concatenate()**函数实现,核心思路是通过计算相邻元素的差值,筛选出符合阈值条件的元素,完全避免显式for循环:

实现代码

import numpy as np

arr = np.array([1.2, 3.4, 3.5, 8.9, 10.9])
threshold = 0.3

# 计算相邻元素的差值
diffs = np.diff(arr)
# 筛选出差值大于等于阈值的位置,拼接第一个元素的索引得到保留列表
keep_indices = np.concatenate([[0], np.where(diffs >= threshold)[0] + 1])
# 获取最终结果
result = arr[keep_indices]

print(result)
# 输出: [ 1.2  3.4  8.9 10.9]

原理说明

  • np.diff(arr):计算数组相邻元素的差值,示例中得到array([2.2, 0.1, 5.4, 2. ])
  • np.where(diffs >= threshold)[0]:找出差值≥0.3的索引(示例中为array([0, 2, 3])),加1后得到这些差值对应的后一个元素索引array([1, 3, 4])
  • 拼接第一个元素的索引[0],最终得到要保留的元素索引[0,1,3,4],用该索引取原数组即可得到目标结果

扩展调整

如果需要保留每组相似元素的最后一个而非第一个,只需修改索引逻辑:

keep_indices = np.concatenate([np.where(diffs >= threshold)[0], [len(arr)-1]])
result = arr[keep_indices]
# 输出: [ 1.2  3.5  8.9 10.9]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 02:45:35