Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python numpy array of numpy arrays

Tags:

I've got a problem on creating a numpy array of numpy arrays. I would create it in a loop:

a=np.array([]) while(...):    ...    b= //a numpy array generated    a=np.append(a,b)    ... 

Desired result:

[[1,5,3], [9,10,1], ..., [4,8,6]] 

Real result:

[1,5,3,9,10,1,... 4,8,6] 

Is it possible? I don't know the final dimension of the array, so I can't initialize it with a fixed dimension.

like image 454
Stefano Sandonà Avatar asked Jul 06 '15 15:07

Stefano Sandonà


People also ask

Can you make a NumPy array of NumPy arrays?

The array of arrays, or known as the multidimensional array, can be created by passing arrays in the numpy. array() function. The following code example shows us how to create an array of arrays or a multidimensional array with the numpy. array() function in Python.

How do I combine multiple NumPy arrays?

You can use the numpy. concatenate() function to concat, merge, or join a sequence of two or multiple arrays into a single NumPy array. Concatenation refers to putting the contents of two or more arrays in a single array.

How do you create an array of arrays in Python?

Array in Python can be created by importing array module. array(data_type, value_list) is used to create an array with data type and value list specified in its arguments.

How do I add NumPy array to NumPy array?

You can append a NumPy array to another NumPy array by using the append() method. In this example, a NumPy array “a” is created and then another array called “b” is created. Then we used the append() method and passed the two arrays.


1 Answers

Never append to numpy arrays in a loop: it is the one operation that NumPy is very bad at compared with basic Python. This is because you are making a full copy of the data each append, which will cost you quadratic time.

Instead, just append your arrays to a Python list and convert it at the end; the result is simpler and faster:

a = []  while ...:     b = ... # NumPy array     a.append(b) a = np.asarray(a) 

As for why your code doesn't work: np.append doesn't behave like list.append at all. In particular, it won't create new dimensions when appending. You would have to create the initial array with two dimensions, then append with an explicit axis argument.

like image 123
nneonneo Avatar answered Sep 24 '22 13:09

nneonneo