Array Indexing
Python · NumPy Library
Theory
Indexing picks elements by position, starting at 0. In a 1-D array, arr[0] is the first value and arr[-1] the last. Slicing uses start:stop:step and stops before stop, so arr[1:4] gives positions 1, 2 and 3, arr[:3] the first three and arr[::-1] the array reversed.
A 2-D array takes one index per axis separated by a comma: arr[row, col]. For a 3 x 4 table of store sales, sales[0, 2] is store 0 in quarter 2, sales[1] (or sales[1, :]) is the whole second row, sales[:, 0] is the first column and sales[1:, 1:3] is the block of rows 1-2 and columns 1-2. A slice keeps the dimension and a single integer drops it, so sales[:, 0] has shape (3,) while sales[:, 0:1] has shape (3, 1).
Why we use it
Analysis constantly needs part of an array: one row, one column, a time window or a block of a matrix. Indexing and slicing get those pieces in one short expression without loops.
When to use it
Use integer indexes and slices when you know the positions. To pick values by a condition use a boolean mask, and to pick a scattered list of positions use fancy indexing. For labelled rows and columns, pandas .loc is clearer.
How it works
- 2-D array sales (3 stores x 4 quarters)
- Pick rows first: an index, a slice or ':' for all
- Then pick columns after the comma
- Used a plain integer on an axis? Yes: That axis is dropped from the result. No: The axis is kept.
- Sub-array (a view of the original)
Syntax
arr[i] arr[-1] arr[start:stop:step]
arr2d[row, col]
arr2d[row_slice, col_slice]
arr2d[:, j]Example
sales = np.array([[120, 135, 150], [90, 95, 110]])
print(sales[1, 2]) # 110
print(sales[:, 0]) # first columnKey points
- Indexes start at 0; negative indexes count from the end
- Slices stop before the stop index
- 2-D indexing is arr[row, col], not arr[row][col] (that works but is slower)
- An integer index drops a dimension; a slice keeps it
- Slices are views: changing them changes the original array