首页 > 解决方案 > 如何在循环中连接 np.ndarray?

问题描述

我有一些 ndarray 值是在循环中构造的。我想将这些 ndarray 连接到轴为 0 的单个数组。我怎么能在 python 中做到这一点?这是我的例子

input: 1x2x32x32x64,1x2x32x32x64,1x2x32x32x64,1x2x32x32x64
output 4x2x32x32x64

我做了什么:

import numpy as np
A_concate=np.array([])
for i in range (4):
    a_i = np.random.rand(1,2,32,32,64)
    print (a_i.shape)
    A_concate= np.concatenate(A_concate,a_i, axis=0)
print (A_concate.shape)

错误

Traceback (most recent call last):
  File "python", line 6, in <module>
TypeError: Argument given by name ('axis') and position (2)

在线代码:https ://repl.it/repls/HugeKnownSolidstatedrive

使用 vstack 的第一个解决方案

import numpy as np
A_concate=[]
for i in range (4):
    a_i = np.random.rand(1,2,32,32,64)
    print (a_i.shape)
    A_concate.append(a_i)
A_concate=np.vstack((A_concate))
print (A_concate.shape)

标签: pythonpython-3.x

解决方案


这是一个解决方案numpy.vstack

import numpy as np
A_stack = np.random.rand(1,2,32,32,64)
for i in range (3):
    a_i = np.random.rand(1,2,32,32,64)
    A_stack= np.vstack([A_stack,a_i])
print (A_stack.shape) # Outputs (4, 2, 32, 32, 64)

推荐阅读