Number of rows in numpy array
<p>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. </p>

<pre><code>a = numpy.array([[1,2,3,4], [2,3,4,5]])
a.shape
&gt;&gt; [2,4]
a.shape[0]
&gt;&gt; 2
a.shape[1]
&gt;&gt; 4
</code></pre>

<p>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</p>

<pre><code>a = numpy.array([1,2,3,4])
a.shape
&gt;&gt; [4,]
a.shape[0]
&gt;&gt; 4    //this is the number of column
a.shape[1]
&gt;&gt; Error out of index
</code></pre>

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

<p>Thank you</p>

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

<p>For a 2D version of the same array, consider the following instead:</p>

<pre><code>&gt;&gt;&gt; a = numpy.array([[1,2,3,4]]) # notice the extra square braces
&gt;&gt;&gt; a.shape
(1, 4)
</code></pre>

python arrays numpy