Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would suggest the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html" rel="nofollow"><code>ravel</code></a> or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html#numpy.ndarray.flatten" rel="nofollow"><code>flatten</code></a> method of <code>ndarray</code>.</p> <pre><code>&gt;&gt;&gt; a = numpy.arange(9).reshape(3, 3) &gt;&gt;&gt; a.ravel() array([0, 1, 2, 3, 4, 5, 6, 7, 8]) </code></pre> <p><code>ravel</code> is faster than <code>concatenate</code> and <code>flatten</code> because it doesn't return a copy unless it has to:</p> <pre><code>&gt;&gt;&gt; a.ravel()[5] = 99 &gt;&gt;&gt; a array([[ 0, 1, 2], [ 3, 4, 99], [ 6, 7, 8]]) &gt;&gt;&gt; a.flatten()[5] = 77 &gt;&gt;&gt; a array([[ 0, 1, 2], [ 3, 4, 99], [ 6, 7, 8]]) </code></pre> <p>But if you need a copy to avoid the memory sharing illustrated above, you're better off using <code>flatten</code> than <code>concatenate</code>, as you can see from these timings: </p> <pre><code>&gt;&gt;&gt; %timeit a.ravel() 1000000 loops, best of 3: 468 ns per loop &gt;&gt;&gt; %timeit a.flatten() 1000000 loops, best of 3: 1.42 us per loop &gt;&gt;&gt; %timeit numpy.concatenate(a) 100000 loops, best of 3: 2.26 us per loop </code></pre> <p>Note also that you can achieve the <em>exact</em> result that your output illustrates (a one-row 2-d array) with <code>reshape</code> (thanks Pierre GM!):</p> <pre><code>&gt;&gt;&gt; a = numpy.arange(9).reshape(3, 3) &gt;&gt;&gt; a.reshape(1, -1) array([[0, 1, 2, 3, 4, 5, 6, 7, 8]]) &gt;&gt;&gt; %timeit a.reshape(1, -1) 1000000 loops, best of 3: 736 ns per loop </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload