Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python List of np arrays to array

I'm trying to turn a list of 2d numpy arrays into a 2d numpy array. For example,

dat_list = [] for i in range(10):     dat_list.append(np.zeros([5, 10])) 

What I would like to get out of this list is an array that is (50, 10). However, when I try the following, I get a (10,5,10) array.

output = np.array(dat_list) 

Thoughts?

like image 524
mike Avatar asked Aug 26 '11 06:08

mike


People also ask

Can I have a list of NumPy arrays?

We can use NumPy np. array tolist() function to convert an array to a list. If the array is multi-dimensional, a nested list is returned. For a one-dimensional array, a list with the array elements is returned.

How do I turn a list into an array?

Create a List object. Add elements to it. Create an empty array with size of the created ArrayList. Convert the list to an array using the toArray() method, bypassing the above-created array as an argument to it.

How do I convert a list to an array in Python?

To convert a list to array in Python, use the np. array() method. The np. array() is a numpy library function that takes a list as an argument and returns an array containing all the list elements.


2 Answers

you want to stack them:

np.vstack(dat_list) 
like image 152
wim Avatar answered Oct 01 '22 10:10

wim


Above accepted answer is correct for 2D arrays as you requested. For 3D input arrays though, vstack() will give you a surprising outcome. For those, use stack(<list of 3D arrays>, 0).

like image 31
Anand Avatar answered Oct 01 '22 08:10

Anand