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

如何从一维numpy数组中提取参考值周边的指定数量元素?

实现方法

你可以直接使用numpy内置的np.searchsorted函数实现该需求,无需手动写for循环。由于np.logspace生成的是严格单调递增的有序数组,该函数可以通过二分查找快速定位到和目标值最接近的索引位置,再按窗口截取即可,执行效率远高于遍历循环。

完整实现代码

import numpy as np

# 初始测试代码
my_array = np.logspace(-1, 2, num=500)
num = 0.9

# 查找目标值对应的插入索引
target_idx = np.searchsorted(my_array, num)
window_size = 30
half_window = window_size // 2

# 计算截取的左右边界,处理数组首尾溢出问题
start_idx = max(0, target_idx - half_window)
end_idx = start_idx + window_size
# 如果右边界超出数组长度,就从末尾往前推窗口长度
if end_idx > len(my_array):
    end_idx = len(my_array)
    start_idx = max(0, end_idx - window_size)

# 提取结果
result = my_array[start_idx:end_idx]
print(result)

运行上述代码得到的输出和你给出的预期结果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:39:02