skywalker
skywalker

Reputation: 1300

What does a numpy shape starting with zero mean

Okay, so I found out that you can have arrays with 0s in their shape.
For the case where you have 0 as the only dimension, this makes sense to me. It is an empty array.

np.zeros(0)

But the case where you have something like this:

np.zeros((0, 100))

Is confusing for me. Why is it defined like this?

Upvotes: 4

Views: 5509

Answers (3)

Youcef4k
Youcef4k

Reputation: 396

It is an empty array that is supposed to be filled in the near future, so the idea is to give your intention of its use. If your use for this array is to store 10 values that represent some metric, you define it as:

np.zeros((0, 10))

instead of empty dimensions with a comment (which are more vulnerable):

np.zeros(0) # This will store 10 values

So at the end of the day, the point is just to make your code more readable with clear intentions for the reader that can your future self.

Upvotes: 0

user10597469
user10597469

Reputation:

Well, in this particular case, the two statements are equivilant:

print(np.zeros(0))
>>>[]

print(np.zeros((0,100)))
>>>[]

This is because an empty array is an empty array. Your intuitions are correct there. If you put in:

np.zeros(10)

or

np.zeros((1,10))

you'd also get the same array, namely [0,0,0,0,0,0,0,0,0,0]. The shape only matters when you are referring to a number that actually changes the shape of the array. For instance:

print(np.zeros((2,3)))
>>>[[0,0,0]
   [0,0,0]]

but:

print(np.zeros((3,2)))
>>>[[0,0]
    [0,0]
    [0,0]]

Nothing particularly opaque about it. Your common sense actually applies here. If an array is empty, none of the other dimensions you add to it matter.

Upvotes: -1

Chicrala
Chicrala

Reputation: 1054

As far as I know it's just a redundant way to express an empty array. It doesn't seems to matter for python if you have rows of "emptiness".

Let's say we have a give array a:

import numpy as np

a = np.zeros((0,100))

If we print a all we get is the empty array itself:

print(a)

>>> []

Moreover we can actually see that despite this a maintain it's shape"

np.shape(a)

>>> (0, 100)

But if you try to access a given element by position, e.g:

print(a[0])

or

print(a[0][0])

You get an IndexError :

IndexError: index 0 is out of bounds for axis 0 with size 0

Therefore I believe that the mathematical meaning of the empty arrays, despite the shape you assign to them, is the same.

Upvotes: 3

Related Questions