NumPy Tutorial menu

NumPy Indexing and Slicing

Indexing picks single values from an array, and slicing picks a range of values.

Indexing a 1-D Array

Indexes start at 0, just like Python lists. Negative indexes count from the end.

Example

python
import numpy as np

temps = np.array([31, 33, 35, 34, 30, 29, 32])
print(temps[0])
print(temps[3])
print(temps[-1])
print(temps[1] + temps[2])
Output
31
34
32
68

Indexing a 2-D Array

Give two numbers separated by a comma: row first, then column.

Example

python
import numpy as np

# rows = students, columns = Maths, English, Science
marks = np.array([
    [85, 72, 90],
    [60, 88, 75],
    [92, 95, 89]
])
print(marks[0, 2])    # first student, Science
print(marks[2, 0])    # third student, Maths
print(marks[1])       # the whole second row
print(marks[-1, -1])  # last row, last column
Output
90
92
[60 88 75]
89

Slicing a 1-D Array

The pattern is [start:stop:step]. The stop index is not included.

Example

python
import numpy as np

arr = np.array([10, 20, 30, 40, 50, 60, 70])
print(arr[1:4])
print(arr[:3])
print(arr[4:])
print(arr[::2])
print(arr[::-1])
Output
[20 30 40]
[10 20 30]
[50 60 70]
[10 30 50 70]
[70 60 50 40 30 20 10]
SliceMeaning
arr[1:4]Index 1, 2, 3
arr[:3]From the start up to index 2
arr[4:]From index 4 to the end
arr[::2]Every second item
arr[::-1]All items in reverse

Slicing a 2-D Array

Slice rows and columns separately, with a comma between them. A single : means "all".

Example

python
import numpy as np

marks = np.array([
    [85, 72, 90],
    [60, 88, 75],
    [92, 95, 89]
])
print(marks[:, 0])      # Maths column for all students
print(marks[0:2, 1:])   # first two students, English and Science
Output
[85 60 92]
[[72 90]
 [88 75]]

Changing Values

You can change one value or a whole slice at once:

Example

python
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
arr[0] = 100
arr[2:4] = 0
print(arr)
Output
[100   2   0   0   5]

Slices Are Views

A slice of a NumPy array is a view: it shares data with the original. If you change the slice, the original changes too. Use .copy() when you want a separate array.

Example

python
import numpy as np

arr = np.array([1, 2, 3, 4])
view = arr[0:2]
copy = arr[0:2].copy()
view[0] = 99
copy[1] = 55
print(arr)
Output
[99  2  3  4]

Changing view changed arr. Changing copy did not.

Fancy Indexing

You can pass a list of indexes to pick several items in any order:

Example

python
import numpy as np

arr = np.array([5, 10, 15, 20, 25])
print(arr[[0, 2, 4]])
Output
[ 5 15 25]

Exercise

Exercise

For a 2-D array m, what does m[:, 1] return?

Learn NumPy with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp