Introduction to NumPy
Indexing and slicing
Slice rows and columns of a 2-D array.
Indexing a 1-D array works like a list: the first element is at index 0.
Indexing a 2-D array uses [row, column], both counted from 0. In the book's marks table (rows for students, columns for subjects), marks[3, 1] is the element in the 4th row and 2nd column (72, Prasad's English marks). An index beyond the last row or column, such as marks[0, 4] in a table with only 3 columns, gives an IndexError.
Slicing extracts part of an array, with the end index excluded:
- 1-D: array8[3:5] gives the elements at indices 3 and 4; array8[::-1] gives the array reversed (it does not sort it).
- 2-D: give a slice for rows and one for columns, separated by a comma: array9[1:3, 0:2] takes rows 1-2 and columns 0-1, that is, the 2nd and 3rd rows and the 1st and 2nd columns.
- A bare colon (:) means all: array9[:, 2] is the whole 3rd column; array9[1, :] would be the whole 2nd row.
Example (new): with sales = np.array([[5, 8, 2], [7, 1, 9], [4, 6, 3], [2, 2, 8]]) (4 shops, 3 days), sales[2, 0] is 4, sales[1:3, 1:] is [[1, 9], [6, 3]], and sales[:, 0] is [5, 7, 4, 2], the first day's sales for every shop.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.