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>Rather then converting this to a 2d array, which may not be an option every time - one could either check the <code>len()</code> of the tuple returned by shape or just check for an index error as such:</p>

<pre><code>import numpy

a = numpy.array([1,2,3,4])
print(a.shape)
# (4,)
print(a.shape[0])
try:
    print(a.shape[1])
except IndexError:
    print("only 1 column")
</code></pre>

<p>Or you could just try and assign this to a variable for later use (or return or what have you) if you know you will only have 1 or 2 dimension shapes:</p>

<pre><code>try:
    shape = (a.shape[0], a.shape[1])
except IndexError:
    shape = (1, a.shape[0])

print(shape)
</code></pre>

python arrays numpy