Create Multidimensional Zeros Python
35,297
Solution 1
You can multiply a tuple (n,)
by the number of dimensions you want. e.g.:
>>> 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.]]])
Solution 2
>>> sh = (10, 10, 10, 10)
>>> z1 = zeros(10000).reshape(*sh)
>>> z1.shape
(10, 10, 10, 10)
EDIT: while above is not wrong, it's just excessive. @mgilson's answer is better.
Solution 3
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.]]]])
Solution 4
you can make multidimensional array of zeros by using square brackets
array_4D = np.zeros([3,3,3,3])
Author by
Sameer Patel
Updated on July 12, 2022Comments
-
Sameer Patel almost 2 years
I need to make a multidimensional array of zeros.
For two (D=2) or three (D=3) dimensions, this is easy and I'd use:
a = numpy.zeros(shape=(n,n))
or
a = numpy.zeros(shape=(n,n,n))
How for I for higher D, make the array of length n?
-
mgilson about 11 yearsOn second thought, I'm not really sure how this gets you anything that
np.zeros
doesn't already support. How is this better thannp.zeros(sh)
? -
mgilson about 11 yearsThis really isn't any different than my answer other than you're using a list rather than a tuple ...
-
ev-br about 11 years@mgilson: you're right. No need for extra brackets, as well:
np.zeros(sh)
works. -
mgilson about 11 yearsRight, that's what I meant :)