Array indexing and slicing

NumPy provides powerful indexing capabilities for arrays. Indexing capabilities in NumPy became so popular that many of them were added back to Python.

Indexing NumPy arrays, in many ways, is very similar to indexing lists or tuples. There are some differences, which will become apparent as we proceed. To start with, let's create an array that has 100 x 100 dimensions:

In [9]: x = np.random.random((100, 100)) 

Simple integer indexing works by typing indices within a pair of square brackets and placing this next to the array variable. This is a widely used Python construct. Any object that has a __getitem__ method will respond to such indexing. Thus, to access the element in the 42nd row and 87th column, just type this:

In [10]: y = x[42, 87] 

Like lists and other Python sequences, the use of a colon to index a range of values is also supported. The following statement will print the k th row of the x matrix.

In [11]: print(x[k, :]) 

The colon can be thought of as an all elements character. So, the preceding statement actually means Print all the characters for the k th row. Similarly, a column can be accessed with x[:,k]. Reversing an array is also similar to reversing a list, such as x[::-1].

The indexed portion of an array is also called a slice of an array, which creates a copy of a port or the whole array (we will cover copies and views in a later section). In the context of an array, the words "slicing" and "indexing" can generally be used interchangeably.

A very concise overview of different slicing and indexing techniques is shown in the following image:

Array indexing and slicing

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.21.175