问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/53747948/what-does-a-numpy-shape-starting-with-zero-mean