Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the shape of a numpy.array

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)?

like image 640
Kyungmin Kim Avatar asked Oct 24 '25 14:10

Kyungmin Kim


2 Answers

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]])
like image 174
Leon Markes Avatar answered Oct 27 '25 02:10

Leon Markes


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.

like image 37
Pierre D Avatar answered Oct 27 '25 03:10

Pierre D