[英]Create Multidimensional Zeros Python
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: 对于两个(D = 2)或三个(D = 3)尺寸,这很容易,我会使用:
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? 如何为更高的D,制作长度为n的数组?
You can multiply a tuple (n,)
by the number of dimensions you want. 您可以将元组
(n,)
乘以所需的维数。 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.]]])
>>> 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.
@ mgilson的答案更好。
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.]]]])
你可以使用方括号制作多维零数组
array_4D = np.zeros([3,3,3,3])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.