Creating Python Multidimensional Zeros

I need to make a multidimensional array of zeros.

For two (D = 2) or three (D = 3) measurements, this is easy, and I would use:

a = numpy.zeros(shape=(n,n)) 

or

a = numpy.zeros(shape=(n,n,n))

How for i for higher D to make an array of length n?

+5
source share
3 answers

You can multiply the tuple (n,)by the number of sizes needed. eg:.

>>> import numpy as np
>>> N=2
>>> np.zeros((N,)*1)
array([ 0.,  0.])
>>> np.zeros((N,)*2)
array([[ 0.,  0.],
       [ 0.,  0.]])
>>> np.zeros((N,)*3)
array([[[ 0.,  0.],
        [ 0.,  0.]],

       [[ 0.,  0.],
        [ 0.,  0.]]])
+11
source
>>> sh = (10, 10, 10, 10)
>>> z1 = zeros(10000).reshape(*sh)
>>> z1.shape
(10, 10, 10, 10)

EDIT: as long as the above is not mistaken, this is just overkill. @mgilson answer is better.

+2
source
In [4]: import numpy

In [5]: n = 2

In [6]: d = 4

In [7]: a = numpy.zeros(shape=[n]*d)

In [8]: a
Out[8]: 
array([[[[ 0.,  0.],
         [ 0.,  0.]],

        [[ 0.,  0.],
         [ 0.,  0.]]],


       [[[ 0.,  0.],
         [ 0.,  0.]],

        [[ 0.,  0.],
         [ 0.,  0.]]]])
+2
source

All Articles