Easy Tutorial
❮ Numpy Tutorial Numpy String Functions ❯

NumPy Slicing and Indexing

The contents of an ndarray object can be accessed and modified by indexing or slicing, similar to the slicing operations in Python's list.

ndarray arrays can be indexed using subscripts from 0 to n. Slice objects can be created using the built-in slice function and setting the start, stop, and step parameters to slice a new array from the original array.

Example

import numpy as np

a = np.arange(10)
s = slice(2, 7, 2)  # Start at index 2, stop at index 7, step by 2
print(a[s])

Output:

[2 4 6]

In the above example, we first create an ndarray object using the arange() function. Then, we set the start, stop, and step parameters to 2, 7, and 2, respectively.

We can also perform slicing operations using the colon-separated slice parameters start:stop:step:

Example

import numpy as np

a = np.arange(10)
b = a[2:7:2]  # Start at index 2, stop at index 7, step by 2
print(b)

Output:

[2 4 6]

Explanation of the colon :: If only one parameter is placed, such as [2], it will return the single element corresponding to that index. If it is [2:], it means all items from that index onwards will be extracted. If two parameters are used, such as [2:7], then the items between the two indices (excluding the stop index) will be extracted.

Example

import numpy as np

a = np.arange(10)  # [0 1 2 3 4 5 6 7 8 9]
b = a[5]
print(b)

Output:

5

Example

import numpy as np

a = np.arange(10)
print(a[2:])

Output:

[2 3 4 5 6 7 8 9]

Example

import numpy as np

a = np.arange(10)  # [0 1 2 3 4 5 6 7 8 9]
print(a[2:5])

Output:

[2 3 4]

The above indexing methods also apply to multi-dimensional arrays:

Example

import numpy as np

a = np.array([[1, 2, 3], [3, 4, 5], [4, 5, 6]])
print(a)
# Slicing from a certain index
print('Slicing from array index a[1:]')
print(a[1:])

Output:

[[1 2 3]
 [3 4 5]
 [4 5 6]]
Slicing from array index a[1:]
[[3 4 5]
 [4 5 6]]

Slicing can also include ellipses ... to make the length of the selection tuple match the dimensions of the array. If an ellipsis is used in the row position, it will return an ndarray containing the elements in the row.

Example

import numpy as np

a = np.array([[1, 2, 3], [3, 4, 5], [4, 5, 6]])
print(a[..., 1])  # Elements in the second column
print(a[1, ...])  # Elements in the second row
print(a[..., 1:])  # The second column and all remaining elements

Output:

[2 4 5]
[3 4 5]
[[2 3]
 [4 5]
 [5 6]]
❮ Numpy Tutorial Numpy String Functions ❯