我有一个返回numpy.ndarray
的函数。该函数在循环中被调用。我希望在循环结束后访问所有numpy.ndarrays
,以便我可以执行numpy操作。
伪代码:
for x in something:
rects = method_that_returns_numpy_arrays()
#at this point I would like access to all the rects collected when the loop ends
我尝试将它们放在一个列表中:
all_rects = []
for x in something:
rects = method_that_returns_numpy_arrays()
all_rects.append(rects)
#now all_rects is a list containing numpy arrays
#but now I can't perform numpy functions such as
#np.column_stack([all_rects[:,0], all_rects[:,1], all_rects[:,2]+all_rects[:,0], all_rects[:,3]+all_rects[:,1]])
问题
如何在循环结束后获得所有rects
的numpy数组?我应该补充一点,我无权更改method_that_returns_numpy_arrays
答案 0 :(得分:0)
您可以使用numpy.column_stack
将列表中的所有rect连接成2D数组。
all_rects = [np.arange(4), np.arange(5, 9)]
rect_array = np.column_stack(all_rects)
array([[0, 5],
[1, 6],
[2, 7],
[3, 8]])
获取您尝试获取的值(通过将元素0添加到元素2,将元素1添加到元素4)。我们可以使用新的numpy数组执行以下操作。
rect_array[2,:] += rect_array[0,:]
rect_array[4,:] += rect_array[1,:]