简体   繁体   English

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

[英]How could I concatenate np.ndarray in loop?

I have some ndarray that values is constructed in loop. 我有一些ndarray值构造在循环中。 I want to concatenate these ndarray to a single array with axis 0. How could I do it in python? 我想将这些ndarray连接到轴为0的单个数组。如何在python中做到这一点? This is my example 这是我的例子

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

What I have done: 我做了什么:

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)

The error 错误

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

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

First solution using vstack 使用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)

Here is a solution with numpy.vstack 这是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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM