The shape attribute for numpy arrays returns the dimensions of the array. If Y has n rows and m columns, then Y.shape is (n,m). So Y.shape[0] is n.
In [46]: Y = np.arange(12).reshape(3,4)
In [47]: Y
Out[47]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [48]: Y.shape
Out[48]: (3, 4)
In [49]: Y.shape[0]
Out[49]: 3
Answer from unutbu on Stack OverflowThe shape attribute for numpy arrays returns the dimensions of the array. If Y has n rows and m columns, then Y.shape is (n,m). So Y.shape[0] is n.
In [46]: Y = np.arange(12).reshape(3,4)
In [47]: Y
Out[47]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [48]: Y.shape
Out[48]: (3, 4)
In [49]: Y.shape[0]
Out[49]: 3
shape is a tuple that gives dimensions of the array..
>>> c = arange(20).reshape(5,4)
>>> c
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]])
c.shape[0]
5
Gives the number of rows
c.shape[1]
4
Gives number of columns
Videos
And if so, which is better to use?
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.
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.