Is there any performance reason to use ndim 1 or 2 vectors in numpy?
<p>This seems like a pretty basic question, but I didn't find anything related to it on stack. Apologies if I missed an existing question.</p>

<p>I've seen some mathematical/linear algebraic reasons why one might want to use numpy vectors "proper" (i.e. ndim 1), as opposed to row/column vectors (i.e. ndim 2).</p>

<p>But now I'm wondering: are there any (significant) <strong>efficiency</strong> reasons why one might pick one over the other? Or is the choice pretty much arbitrary in that respect? </p>

<p>(edit) To clarify: By "ndim 1 vs ndim 2 vectors" I mean representing a vector that contains, say, numbers 3 and 4 as either:</p>

<ul>
<li><p>np.array([3, 4]) # ndim 1</p></li>
<li><p>np.array([[3, 4]]) # ndim 2</p></li>
</ul>

<p>The numpy documentation seems to lean towards the first case as the default, but like I said, I'm wondering if there's any <em>performance</em> difference.</p>

<p>If you use numpy properly, then no - it is not a consideration.</p>

<p>If you look at the <a href="https://docs.scipy.org/doc/numpy/reference/internals.html" rel="nofollow">numpy internals documentation</a>, you can see that</p>

<blockquote>
  <p>Numpy arrays consist of two major components, the raw array data (from now on, referred to as the data buffer), and the information about the raw array data. The data buffer is typically what people think of as arrays in C or Fortran, a contiguous (and fixed) block of memory containing fixed sized data items. Numpy also contains a significant set of data that describes how to interpret the data in the data buffer.</p>
</blockquote>

<p>So, irrespective of the dimensions of the array, all data is stored in a continuous buffer. Now consider</p>

<pre><code>a = np.array([1, 2, 3, 4])
</code></pre>

<p>and</p>

<pre><code>b = np.array([[1, 2], [3, 4]])
</code></pre>

<p>It is true that accessing <code>a[1]</code> requires (slightly) less operations than <code>b[1, 1]</code> (as the translation of <code>1, 1</code> to the flat index requires some calculations), but, for high performance, <a href="https://www.safaribooksonline.com/library/view/python-for-data/9781449323592/ch04.html" rel="nofollow">vectorized operations</a> are required anyway. </p>

<p>If you want to sum all elements in the arrays, then, in both case you would use the same thing: <code>a.sum()</code>, and <code>b.sum()</code>, and the sum would be over elements in contiguous memory anyway. Conversely, if the data is inherently 2d, then you could do things like <code>b.sum(axis=1)</code> to sum over rows. Doing this yourself in a 1d array would be error prone, and not more efficient.</p>

<p>So, basically a 2d array, if it is natural for the problem just gives greater functionality, with zero or negligible overhead.</p>

python numpy vector