10

I want to make an 4 dimensional array of zeros in python. 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

0

3 Answers 3

7

You can use np.full:

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

numpy.full

Return a new array of given shape and type, filled with 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.]]]])
Sign up to request clarification or add additional context in comments.

Comments

4

You can pass more than one arg to shape:

shape : int or sequence of ints Shape of the new array, e.g., (2, 3) or 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

1 Comment

I didn't know you could pass args to shape. Good to know.
0

As of Python v. 3.50, using the np.full command returns

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. Both work for now, though!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.