简体   繁体   中英

Stack a list of numpy arrays

I have a list of numpy arrays that are of the following shapes:

(16, 250, 2)
(7, 250, 2)
(1, 250, 2)

I'm trying to stack them all together so they are a single numpy array of shape:

(24, 250, 2)

I tried using np.stack but I get the error:

ValueError: all input arrays must have the same shape

You can use np.concatenate: You will get this:-

a = np.random.rand(16,250,2)
b = np.random.rand(7,250,2)
c = np.random.rand(1,250,2)
print(np.shape(np.concatenate([a,b,c], axis=0))

Output:

(24,250,2)

The trick is to use the right stacking method, in your case since you are stacking vertically you should use np.vstack

import numpy as np

a = np.random.random((16, 250, 2))
b = np.random.random((7, 250, 2))
c = np.random.random((1, 250, 2))

arr = np.vstack((a,b,c))
arr.shape
(24, 250, 2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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