如何将两个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
相关产品推荐
相关产品推荐

