Reputation: 69
If the array x
is declared as:
x = np.array([[1, 2], [3, 4]])
the shape of x
is (2, 2)
because it is a 2x2 matrix.
However, for a 1-dimensional vector, such as:
x = np.array([1, 2, 3])
why does the shape of x
gives (3,)
and not (1,3)
?
Is it my mistake to understand the shape as (row, column)
?
Upvotes: 4
Views: 3732
Reputation: 52139
np.array
represents an n-dimensional array. This may include a 2-dimensional array to represent a matrix, for which (row, column)
is appropriate. It may also include 1-dimensional, 3-dimensional or other arrays for which (row, column)
are too many/few dimensions. Compare:
>>> # 1-dimensional
>>> np.array([1, 2, 3]).shape
(3,)
>>> np.array([1, 2, 3])[1]
2
>>> # 2-dimensional
>>> np.array([[1, 2, 3]]).shape
(1, 3)
>>> np.array([[1, 2, 3]])[0,1]
2
>>> np.array([[1], [2], [3]]).shape
(3, 1)
>>> np.array([[1], [2], [3]])[1, 0]
2
>>> # 3-dimensional
>>> np.array([[[1, 2, 3]]]).shape
(1, 1, 3)
>>> np.array([[[1, 2, 3]]])[0,0,1]
2
>>> np.array([[[1,2],[3,4]],[[5, 6], [7, 8]]]).shape
(2, 2, 2)
Note how the shapes (3,)
, (1, 3)
, (3, 1)
, (1, 1, 3)
, ... represent different logical layouts, as exemplified by the different position at which a specific element resides.
Upvotes: 1
Reputation: 26271
As per the docs, np.array
's are multidimensional containers. Consider:
np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]).shape
# (2, 2, 2)
Also, np.shape always returns a tuple. In your example, (3,)
is the representation of a one-element tuple, which is the correct value for the shape of a one-dimensional array.
Upvotes: 1
Reputation: 442
Because np.array([1,2,3])
is one-dimensional array. (3,)
means that this is single dimension with three elements.
(1,3)
means that this is a two-dimensional array.
If you use reshape()
method on the array, and give it arguments (1,3)
, additional brackets will be added to it.
>>> np.array([1,2,3]).reshape(1,3)
array([[1, 2, 3]])
Upvotes: 5