Indexing on NumPy Arrays:

  • Just as we can index and slice Python lists to access individual data elements or groups of elements, we can also index and slice NumPy arrays using the same square bracket operator.
  • Because NumPy arrays can be multidimensional, we can index or slice in one or more dimensions.
  • Example: The below array, a, is a 2D NumPy array with four rows and five columns.
python
1import numpy as np
2
3a = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], 
4[15, 16, 17, 18, 19]])
5
6print(a)
7print(a.shape)
8print(a.dtype)

Output:

1[[ 0  1  2  3  4]
2 [ 5  6  7  8  9]
3 [10 11 12 13 14]
4 [15 16 17 18 19]]
5(4, 5)
6int32

Slicing NumPy Arrays

  • To access particular elements, we can use the square bracket operator and specify the row and column indicies of the element we want to access.
    • For example, the a[1,1] means we’re in index position 1 along the rows, and index position 1 along the columns.
python
9print(a[1,1])

Output: That gives us this element 6.

16

Slicing Subarrays from NumPy Arrays:

  • We can also slice out pieces of subarrays from the data.
    • For example, we can get the data that are in row position 0 and from index positions 2 through 5.
python
10print(a[0, 2:5])

Output:

1[2 3 4]

Boolean and Logical Indexing:

  • We can also use Boolean and logical indexing to select elements from a NumPy array.
  • For example, we can use a Boolean expression to select all elements in the array that are greater than 0.5.
  • The expression a>0.5 returns a Boolean array of the same shape as a with True values where the condition is met and False values where it is not.
  • We can then use this Boolean array to index into the original array and select only the elements that meet the condition.
python
1a = np.random.random(10)
2print(a)
3print(a>0.5)
4print(a[a>0.5])

Output:

1[0.78359399 0.03683155 0.89489439 0.10628599 0.1746632  0.14924692
2 0.54125723 0.98866927 0.13709147 0.74078514]
3[ True False  True False False False  True  True False  True]
4[0.78359399 0.89489439 0.54125723 0.98866927 0.74078514]