Saturday, October 10, 2020

Array-Oriented Programming with NumPy- 8 (Indexing and Slicing)


One-dimensional arrays can be indexed and sliced using the same syntax and techniques we use for Lists and Tuples”. Here, we focus on array-specific indexing and slicing capabilities.

Indexing with Two-Dimensional arrays

To select an element in a two-dimensional array, specify a tuple containing the element’s row and column indices in square brackets (as in snippet [4]):

In [1]: import numpy as np
In [2]: grades = np.array([[87, 96, 70], [100, 87, 90],
...: [94, 77, 90], [100,81, 82]])
...:
 

In [3]: grades

Out[3]:
array([[ 87, 96, 70],
[100, 87, 90],
[ 94, 77, 90],
[100, 81, 82]])
 

In [4]: grades[0, 1] # row 0, column 1
Out[4]: 96 

Selecting a Subset of a Two-Dimensional array’s Rows 

To select a single row, specify only one index in square brackets:

In [5]: grades[1]
Out[5]: array([100, 87, 90])

To select multiple sequential rows, use slice notation:

In [6]: grades[0:2]
Out[6]:
array([[ 87, 96, 70],
[100, 87, 90]])

To select multiple non-sequential rows, use a list of row indices:

In [7]: grades[[1, 3]]
Out[7]:
array([[100, 87, 90],
[100, 81, 82]])

Selecting a Subset of a Two-Dimensional array’s Columns

You can select subsets of the columns by providing a tuple specifying the row(s) and column(s) to select. Each can be a specific index, a slice or a list. Let’s select only the elements in the first column:

In [8]: grades[:, 0]
Out[8]: array([ 87, 100, 94, 100])

The 0 after the comma indicates that we’re selecting only column 0. The : before the comma indicates which rows within that column to select. In this case, : is a slice representing all rows. This also could be a specific row number, a slice representing a subset of the rows or a list of specific row indices to select, as in snippets [5]–[7].

You can select consecutive columns using a slice:

In [9]: grades[:, 1:3]
Out[9]:
array([[96, 70],
[87, 90],
[77, 90],
[81, 82]])

or specific columns using a list of column indices:

In [10]: grades[:, [0, 2]]
Out[10]:
array([[ 87, 70],
[100, 90],
[ 94, 90],
[100, 82]])


Share:

0 comments:

Post a Comment