NumPy · Lesson 1.2
Indexing and slicing
Pick single values, ranges, rows and columns out of an array, and know when you're changing the original.
1One dimension
Indexing works like a list: arr[0] is the first value, arr[-1] the last, and arr[2:5] the values at positions 2, 3 and 4.
import numpy as np temps = np.array([18, 21, 19, 25, 27, 24, 22]) print(temps[0], temps[-1]) print(temps[2:5]) print(temps[::2])
Practice
Store the last 3 daily sign-up counts.
import numpy as np signups = np.array([40, 52, 38, 61, 70, 66, 59, 73]) result = ...
2Rows and columns
In a 2D array, arr[row, col] picks one value. A : means "all of them", so arr[1, :] is a whole row and arr[:, 2] a whole column.
import numpy as np # rows are users, columns are weeks sessions = np.array([[5, 3, 6, 2], [0, 1, 4, 4], [7, 8, 2, 5]]) print(sessions[2, 0]) print(sessions[1, :]) print(sessions[:, 2])
Practice
Store the sessions of every user in week 3 (the third column).
import numpy as np sessions = np.array([[5, 3, 6, 2], [0, 1, 4, 4], [7, 8, 2, 5]]) result = ...
3Blocks of rows and columns
Slices work on both axes at once: arr[0:2, 1:3] takes rows 0 and 1, and columns 1 and 2. The result is a smaller grid.
import numpy as np grid = np.arange(1, 21).reshape(4, 5) print(grid) print(grid[1:3, 2:])
Practice
Store the sessions of the first 2 users in the last 2 weeks, as a 2 by 2 array.
import numpy as np sessions = np.array([[5, 3, 6, 2], [0, 1, 4, 4], [7, 8, 2, 5]]) result = ...
4Slices share memory
A slice is a view of the original array, so changing it changes the original too. Call .copy() when you want a separate array to change freely.
import numpy as np prices = np.array([10, 20, 30, 40]) first_two = prices[:2] first_two[0] = 99 print(prices) safe = prices[:2].copy() safe[0] = 0 print(prices)
Practice
Make a copy of the first 3 values of stock, set the copy's first value to 0, and store the original stock array (it should be unchanged).
import numpy as np stock = np.array([12, 7, 3, 15, 9]) part = stock[:3] part[0] = 0 result = ...