Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a multidimension numpy array with a varying row size?

I would like to create a two dimensional numpy array of arrays that has a different number of elements on each row.

Trying

cells = numpy.array([[0,1,2,3], [2,3,4]]) 

gives an error

ValueError: setting an array element with a sequence. 
like image 292
D R Avatar asked Aug 02 '10 08:08

D R


People also ask

Can you add arrays with different dimensions?

Ahh your array_2 only has one dimension, needs to have same number of dimensions with your array_1 . You can either reshape it array_2. reshape(-1,1) , or add a new axis array_2[:,np. newaxis] to make it 2 dimensional before concatenation.

Can be used to alter the size of a NumPy array?

Size of a numpy array can be changed by using resize() function of the NumPy library.


1 Answers

We are now almost 7 years after the question was asked, and your code

cells = numpy.array([[0,1,2,3], [2,3,4]]) 

executed in numpy 1.12.0, python 3.5, doesn't produce any error and cells contains:

array([[0, 1, 2, 3], [2, 3, 4]], dtype=object) 

You access your cells elements as cells[0][2] # (=2) .

An alternative to tom10's solution if you want to build your list of numpy arrays on the fly as new elements (i.e. arrays) become available is to use append:

d = []                 # initialize an empty list a = np.arange(3)       # array([0, 1, 2]) d.append(a)            # [array([0, 1, 2])] b = np.arange(3,-1,-1) #array([3, 2, 1, 0]) d.append(b)            #[array([0, 1, 2]), array([3, 2, 1, 0])] 
like image 184
calocedrus Avatar answered Sep 27 '22 22:09

calocedrus