简体   繁体   English

python中的4维零点数组

[英]4 dimensional array of zeros in python

I want to make an 4 dimensional array of zeros in python. 我想在python中创建一个4维的零数组。 I know how to do this for a square array but I want the lists to have different lengths. 我知道如何为方阵做这个,但我希望列表有不同的长度。

Right now I use this: 现在我用这个:

numpy.zeros((200,)*4)

Which gives them all length 200 but I would like to have lengths 200,20,100,20 because now I have a lot of zeros in my array that I don't use 这给了他们所有的长度200,但我想有200,20,100,20长度,因为现在我的阵列中有很多零,我不使用

You can use np.full : 你可以使用np.full

>>> np.full((200,20,10,20), 0)

numpy.full numpy.full

Return a new array of given shape and type, filled with fill_value. 返回给定形状和类型的新数组,填充fill_value。

Example : 示例:

>>> np.full((1,3,2,4), 0)
array([[[[ 0.,  0.,  0.,  0.],
         [ 0.,  0.,  0.,  0.]],

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

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

You can pass more than one arg to shape: 您可以将多个arg传递给shape:

shape : int or sequence of ints Shape of the new array, eg, (2, 3) or 2. shape:int或int of sequence新数组的形状,例如(2,3)或2。

In [26]: arr = np.zeros((200, 20, 10, 20))

In [27]: arr.shape
Out[27]: (200, 20, 10, 20)

It also seems a lot more efficient when you have large dimensions: 当你有大尺寸时,它似乎也更有效:

In [43]: timeit arr = np.full((200, 100, 100, 100),0)
1 loops, best of 3: 232 ms per loop

In [44]: timeit arr = np.zeros((200, 100, 100, 100))
100000 loops, best of 3: 12.6 µs per loop
In [45]: timeit arr = np.zeros((500, 100, 100, 100))
100000 loops, best of 3: 13.5 µs per loop    
In [46]: timeit arr = np.full((500, 100, 100, 100),0)
1 loops, best of 3: 1.19 s per loop

As of Python v. 3.50, using the np.full command returns 从Python np.full ,使用np.full命令返回

FutureWarning: in the future, full((1, 3, 2, 4), 0) will return an array of dtype('int32') . FutureWarning: in the future, full((1, 3, 2, 4), 0) will return an array of dtype('int32')

Based on this, I'd plug @Padriac's answer. 基于此,我插上@ Padriac的答案。 Both work for now, though! 但两者现在都可以使用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM