Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Numpy is incredibly flexible and powerful when it comes to views into arrays whilst minimising copies. For example:</p> <pre><code>import numpy a = numpy.random.randint(0, 10, size=10) b = numpy.a[3:10] </code></pre> <p>b is now a view of the original array that was created.</p> <p>Numpy arrays allow all manner of access directly to the data buffers, and can be trivially typecast. For example:</p> <pre><code>a = numpy.random.randint(0, 10, size=10) b = numpy.frombuffer(a.data, dtype='int8') </code></pre> <p>b is now view into the memory with the data all as 8-bit integers (the data itself remains unchanged, so that each 64-bit int now becomes 8 8-bit ints). These buffer objects (from a.data) are standard python buffer objects and so can be used in all the places that are defined to work with buffers.</p> <p>The same is true for multi-dimensional arrays. However, you have to bear in mind how the data lies in memory. For example:</p> <pre><code>a = numpy.random.randint(0, 10, size=(10, 10)) b = numpy.frombuffer(a[3,:].data, dtype='int8') </code></pre> <p>will work, but</p> <pre><code>b = numpy.frombuffer(a[:,3].data, dtype='int8') </code></pre> <p>returns an error about being unable to get single-segment buffer for discontiguous arrays. This problem is not obvious because simply allocating that same view to a variable using</p> <pre><code>b = a[:,3] </code></pre> <p>returns a perfectly adequate numpy array. However, it is not contiguous in memory as it's a view into the other array, which need not be (and in this case isn't) a view of contiguous memory. You can get info about the array using the flags attribute on an array:</p> <pre><code>a[:,3].flags </code></pre> <p>which returns (among other things) both C_CONTIGUOUS (C order, row major) and F_CONTIGUOUS (Fortran order, column major) as False, but </p> <pre><code>a[3,:].flags </code></pre> <p>returns them both as True (in 2D arrays, at most one of them can be true).</p>
 

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