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

如何将两个numpy数组拼接为[[i, pred, boxes],…]格式的新数组

问题原因

你原来的代码不生效的核心原因是np.insert不属于原地操作,执行后会返回修改后的新数组,你没有将返回结果赋值给对应变量,所以原数组始终没有变化。

可行实现方案

推荐用numpy的向量化拼接操作,不需要循环,效率更高,实现代码如下:

import numpy as np

# 假设你已经定义好了这两个数组
prediction_score = np.array([0.99764085, 0.26231623, 0.07232302])
prediction_boxes = np.array([
    [282.25906, 79.13187, 420.98575, 226.11221],
    [109.91688, 94.8121, 333.07764, 225.87985],
    [340.3894, 96.612015, 601.4172, 231.13196]
])
i = 1

# 构造需要插入的两列,统一转成n行1列的二维数组
i_col = np.full((len(prediction_score), 1), i)
score_col = prediction_score.reshape(-1, 1)

# 按列拼接三个数组得到最终结果
result = np.concatenate([i_col, score_col, prediction_boxes], axis=1)
print(result)

运行后输出的结果就完全符合你要的[[i, pred, boxes],…]格式。

如果你一定要用循环的方式修改你原来的代码,也可以按下面的写法调整,但数组长度大的时候效率远低于上面的向量化方案:

import numpy as np

prediction_score = np.array([0.99764085, 0.26231623, 0.07232302])
prediction_boxes = np.array([
    [282.25906, 79.13187, 420.98575, 226.11221],
    [109.91688, 94.8121, 333.07764, 225.87985],
    [340.3894, 96.612015, 601.4172, 231.13196]
])
i = 1
result = []
for idx in range(len(prediction_score)):
    # 把insert的结果保存下来
    temp = np.insert(prediction_boxes[idx], 0, prediction_score[idx])
    temp = np.insert(temp, 0, i)
    result.append(temp)
# 转成numpy数组
result = np.array(result)
print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:54:06