Learning IPython for Interactive Computing and Data Visualization by Learning IPython for Interactive Computing & Data Visualization

Learning IPython for Interactive Computing and Data Visualization by Learning IPython for Interactive Computing & Data Visualization

Author:Learning IPython for Interactive Computing & Data Visualization
Language: eng
Format: epub
Publisher: Packt Publishing


More indexing possibilities

More generally, indexing allows us to take any portion of an array. We saw in the previous section how to filter an array with a Boolean condition. We can also specify directly the list of indices we want to keep. For instance, if x is a one-dimensional NumPy array, x[i:j:k] represents a view on x with only those elements having indices between i (included) and j (excluded) with a step of k. If i is omitted, it is assumed to be zero. If j is omitted, it is assumed to be the length of the array in that dimension. Negative values mean we count from the end. Finally, the default value for k is one. This notation is also valid in multiple dimensions; for example, M[i:j,k:l] creates a submatrix view on a 2D array M. Also, we can use x[::-1] to get x in the reverse order.

These conventions, with i included and j excluded, are convenient when working with consecutive portions of an array. For example, the first and second halves of x, assuming a size 2n, are simply x[:n] and x[n:]. In addition, the length of x[i:j] is simply j - i. In the end, there should not be +1 or -1 values hanging around in indices in general.

An important point to consider with array views is that they point to the same location in memory. So a view on a large array does not imply memory allocation, and changing the values of elements in the view also changes the corresponding values in the original array, as shown in the following example:

In [1]: x = rand(5) In [2]: x Out[2]: array([ 0.5 , 0.633, 0.158, 0.862, 0.35 ]) In [3]: y = x[::2] In [4]: y Out[4]: array([ 0.5 , 0.158, 0.35 ]) In [5]: y[0] = 1 In [6]: x Out[6]: array([ 1. , 0.633, 0.158, 0.862, 0.35 ])



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.