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
(2,)
(1,2)
as its output? Shouldn't it be
(1,2)
(1,2)
instead? I got this in both python 2.7.3 and python 3.2.3
NumPy arrays have an attribute called shape that returns a tuple with each index having the number of corresponding elements.
The shape tool gives a tuple of array dimensions and can be used to change the dimensions of an array. The reshape tool gives a new shape to an array without changing its data. It creates a new array and does not modify the original array itself.
How can we get the Shape of an Array? In NumPy we will use an attribute called shape which returns a tuple, the elements of the tuple give the lengths of the corresponding array dimensions. Parameters: Array is passed as a Parameter. Return: A tuple whose elements give the lengths of the corresponding array dimensions.
Shape (in the numpy context) seems to me the better option for an argument name. The actual relation between the two is size = np. prod(shape) so the distinction should indeed be a bit more obvious in the arguments names. randint uses the size parameter name, but uses shape in the explanation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With