7.10 Indexing and Slicing

  • One-dimensional arrays can be indexed and sliced like lists.

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
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])
  • Select multiple sequential rows with slice notation
In [6]:
grades[0:2]
Out[6]:
array([[ 87,  96,  70],
       [100,  87,  90]])
  • Select multiple non-sequential rows with 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

  • The column index also can be a specific index, a slice or a list
In [8]:
grades[:, 0]
Out[8]:
array([ 87, 100,  94, 100])
In [9]:
grades[:, 1:3]
Out[9]:
array([[96, 70],
       [87, 90],
       [77, 90],
       [81, 82]])
In [10]:
grades[:, [0, 2]]
Out[10]:
array([[ 87,  70],
       [100,  90],
       [ 94,  90],
       [100,  82]])

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.