How can I initialize an empty Numpy array with a given number of dimensions?


I basically want to initialize an empty 6-tensor, like this:

a = np.array([[[[[[]]]]]])

Is there a better way than writing the brackets explicitly?

Asked By: Lenar Hoyt



You can use empty or zeros.

For example, to create a new array of 2×3, filled with zeros, use: numpy.zeros(shape=(2,3))

Answered By: avip

You could directly use the ndarray constructor:

numpy.ndarray(shape=(1,) * 6)

Or the empty variant, since it seems to be more popular:

numpy.empty(shape=(1,) * 6)
Answered By: ChristopherC

Iteratively adding rows of that rank-1 using np.concatenate(a,b,axis=0)

Don’t. Creating an array iteratively is slow, since it has to create a new array at each step. Plus a and b have to match in all dimensions except the concatenation one.

np.concatenate((np.array([[[]]]),np.array([1,2,3])), axis=0)

will give you dimensions error.

The only thing you can concatenate to such an array is an array with size 0 dimenions

In [348]: np.concatenate((np.array([[]]),np.array([[]])),axis=0)
Out[348]: array([], shape=(2, 0), dtype=float64)
In [349]: np.concatenate((np.array([[]]),np.array([[1,2]])),axis=0)
ValueError: all the input array dimensions except for the concatenation axis must match exactly
In [354]: np.array([[]])
Out[354]: array([], shape=(1, 0), dtype=float64)
In [355]: np.concatenate((np.zeros((1,0)),np.zeros((3,0))),axis=0)
Out[355]: array([], shape=(4, 0), dtype=float64)

To work iteratively, start with a empty list, and append to it; then make the array at the end.

a = np.zeros((1,1,1,1,1,0)) could be concatenated on the last axis with another np.ones((1,1,1,1,1,n)) array.

In [363]: np.concatenate((a,np.array([[[[[[1,2,3]]]]]])),axis=-1)
Out[363]: array([[[[[[ 1.,  2.,  3.]]]]]])
Answered By: hpaulj

You can do something like np.empty(shape = [1] * (dimensions - 1) + [0]).

>>> a = np.array([[[[[[]]]]]])
>>> b = np.empty(shape = [1] * 5 + [0])
>>> a.shape == b.shape
Answered By: Marco

This should do it:

x = np.array([])
Answered By: user16952851
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.