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

基于Numpy数组元素位置匹配获取索引并高效填充目标数组

解决方案

首先,注意到你的reference数组其实是从0到14的连续序列,每个位置i对应的元素就是i——这是关键!结合a中所有正值唯一的特性,我们可以用非常直接的纯Numpy操作完成填充:

import numpy as np

a = np.array([8,5,4,-1,-1, 7,-1,-1,12,11,-1,-1,14,-1,-1])
lookup = np.array([3,6,0,-2,-2,24,-2,-2,24,48,-2,-2,84,-2,-2])

# 初始化z数组
z = np.zeros(15)

# 筛选出a中所有正值,以及对应的lookup值
valid_mask = a > 0
target_indices = a[valid_mask]
values_to_fill = lookup[valid_mask]

# 直接将值填充到z的对应索引位置
z[target_indices] = values_to_fill

print(z)
# 输出结果:[ 0.  0.  0.  0.  0.  6.  0. 24.  3.  0.  0. 48. 24.  0. 84.]

为什么这个方法有效?

  1. 利用reference的特性:你的reference[i]等于i,所以z的第i个位置正好对应reference中值为i的元素,不需要额外的索引映射。
  2. 筛选有效数据:通过a > 0的掩码,我们直接提取出a中所有需要匹配的正值(也就是存在于reference中的值),以及lookup中对应的有效值。
  3. 直接索引赋值:Numpy支持用数组作为索引批量赋值,z[target_indices] = values_to_fill会自动把每个values_to_fill中的值放到z对应target_indices的位置上,完全不需要循环,性能拉满。

如果你的reference不是连续的0到n序列,而是任意数组,我们也可以用类似的思路,结合np.searchsorted来实现通用版本:

# 通用场景:reference为任意数组的情况
reference = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14])
a_pos = a[a>0]
lookup_pos = lookup[a>0]

# 找到a_pos在reference中的索引位置
reference_indices = np.searchsorted(reference, a_pos)
# 验证匹配正确性(确保a_pos的元素都在reference中)
assert np.all(reference[reference_indices] == a_pos)

z = np.zeros(reference.size)
z[reference_indices] = lookup_pos

不过在你的特定场景下,第一种方法已经完全满足需求,而且最简单高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 05:17:33