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

如何将Numpy数组元素插入到已有数组的指定索引位置?

问题描述

给定以下Python代码片段:

import numpy as np

pos = np.array([1, 3, 4])
arr = np.array([0, 1, 2, 3, 4, 5])
vals = np.array([[-10,10], [-20,20], [99,66]])

需要将vals中的元素插入到arr中由pos指定的索引位置,最终预期结果为:

result = np.array([0, -10, 10, 1, 2, -20, 20, 3,  99, 66, 4, 5])
解决方案

方法一:批量索引合并(高效版)

通过预计算所有目标位置,一次性完成数组合并,适合处理大规模数据:

import numpy as np

pos = np.array([1, 3, 4])
arr = np.array([0, 1, 2, 3, 4, 5])
vals = np.array([[-10,10], [-20,20], [99,66]])

# 将vals展开为一维数组
vals_flat = vals.flatten()
# 计算插入位置的偏移量:每个插入操作会增加2个元素,需修正后续插入点的位置
offsets = np.cumsum(np.ones_like(pos) * 2) - 2
adjusted_pos = pos + offsets

# 创建结果数组的索引掩码,标记原始arr元素和插入元素的位置
total_len = len(arr) + len(vals_flat)
mask = np.ones(total_len, dtype=bool)
# 标记插入元素的位置为False
insert_positions = np.concatenate([[p, p+1] for p in adjusted_pos])
mask[insert_positions] = False

# 填充结果数组
result = np.empty(total_len, dtype=arr.dtype)
result[mask] = arr
result[~mask] = vals_flat

print(result)
# 输出:[  0 -10  10   1   2 -20  20   3  99  66   4   5]

方法二:循环逐个插入(直观版)

通过循环调用np.insert逐个插入元素,代码更直观易懂,适合小规模数据:

import numpy as np

pos = np.array([1, 3, 4])
arr = np.array([0, 1, 2, 3, 4, 5])
vals = np.array([[-10,10], [-20,20], [99,66]])

result = arr.copy()
# 按顺序插入,每次插入后后续位置会自动偏移
for p, v in zip(pos, vals):
    result = np.insert(result, p, v)

print(result)
# 输出:[  0 -10  10   1   2 -20  20   3  99  66   4   5]
说明
  • 方法一通过预计算所有位置,避免多次数组复制,性能更优;
  • 方法二代码逻辑简单,可读性强,但每次插入都会生成新数组,数据量较大时效率较低。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:16:18