Yichuan Wang Yichuan Wang - 9 months ago 58
Python Question

Number of rows in numpy array

I know that numpy array has a method called shape that returns [No.of rows, No.of columns], and shape[0] gives you the number of rows, shape[1] gives you the number of columns.

a = numpy.array([[1,2,3,4], [2,3,4,5]])
>> [2,4]
>> 2
>> 4

However, if my array only have one row, then it returns [No.of columns, ]. And shape[1] will be out of the index. For example

a = numpy.array([1,2,3,4])
>> [4,]
>> 4 //this is the number of column
>> Error out of index

Now how do I get the number of rows of an numpy array if the array may have only one row?

Thank you


The concept of rows and columns applies when you have a 2D array. However, the array numpy.array([1,2,3,4]) is a 1D array and so has only one dimension, therefore shape rightly returns a single valued iterable.

For a 2D version of the same array, consider the following instead:

>>> a = numpy.array([[1,2,3,4]]) # notice the extra square braces
>>> a.shape
(1, 4)