如何在循环中连接np.ndarray?

时间:2018-11-15 16:18:56

标签: python python-3.x

我有一些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)

1 个答案:

答案 0 :(得分:2)

这是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)