Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.shape gives inconsistent responses - why?

Tags:

python

numpy

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

like image 248
APR Avatar asked Sep 30 '12 22:09

APR


People also ask

What does the shape method in NumPy return?

NumPy arrays have an attribute called shape that returns a tuple with each index having the number of corresponding elements.

What is the difference between shape and reshape in NumPy?

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 would you describe the shape of a NumPy array?

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.

What is the difference between shape and size in NumPy?

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.


1 Answers

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

  • You start with an array : 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,)
  • Consider 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
  • Consider c=np.array([[1,],[2,]]). Another 2D array, with 2 rows, 1 column: c.shape=(2,1) and len(c)=2.
  • Consider 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.

like image 56
Pierre GM Avatar answered Sep 17 '22 23:09

Pierre GM