Why does the program
import numpy as np
c = np.array([1,2])
print(c.shape)
d = np.array([[1],[2]]).transpose()
print(d.shape)
give
<
When you invoke the .shape
attribute of a ndarray
, you get a tuple with as many elements as dimensions of your array. The length, ie, the number of rows, is the first dimension (shape[0]
)
c=np.array([1,2])
. That's a plain 1D array, so its shape will be a 1-element tuple, and shape[0]
is the number of elements, so c.shape = (2,)
c=np.array([[1,2]])
. That's a 2D array, with 1 row. The first and only row is [1,2]
, that gives us two columns. Therefore, c.shape=(1,2)
and len(c)=1
c=np.array([[1,],[2,]])
. Another 2D array, with 2 rows, 1 column: c.shape=(2,1)
and len(c)=2
.d=np.array([[1,],[2,]]).transpose()
: this array is the same as np.array([[1,2]])
, therefore its shape is (1,2)
.Another useful attribute is .size
: that's the number of elements across all dimensions, and you have for an array c
c.size = np.product(c.shape)
.
More information on the shape in the documentation.