December 29, 2019python courses
This video covers how to index and modify multidimensional NumPy arrays.
import numpy as np # make a new, 3x4 array from list of lists bar = np.array([ [5, 10, 15, 20], [25, 30, 35, 40], [45, 50, 55, 60] ]) # return the element at position (1,2) bar[1, 2] # return row 1 as a 1d array bar # return row 1 as a 2d array bar[0, None] # return the 2nd and 3rd columns in rows 2-3 bar[1:3, [-2, -1]] # replace element (0, 0) with -1 bar[0, 0] = -1 # replace the 2nd row using the 3rd row bar = bar # insert 0s on diagonal bar[[0, 1, 2], [0, 1, 2]] = [0, 0, 0]
In this section, we’ll see how to work with multidimensional arrays. We’ll start by making a new 3x4 array called “bar”. Before we start accessing elements from this array, it’s important to understand its structure.
Internally, bar is just a contiguous block of memory storing some data. Being a contiguous block of memory is what makes numpy arrays fast. Since we defined bar using a list of lists, numpy makes it a two dimensional array, giving it two axes for indexing its values. Since this array has two dimensions, or, axes, numpy knows to interpret our data as a rectangular array where axis 0 is the row axis and axis 1 is the column axis.
This means we can subset bar using a combination of row indices and column indices.
Let’s see some examples using the 2d array we just created.
If you want to get the element at index (1,2) just use bar, square brackets, one comma two.
If you want to get the entire first row as a 1d array, use bar square brackets zero. Remember, bar can be interpreted as an array of arrays, so the 1st element of bar is just a 1d array.
If you want to get the entire first row as a 2d array, use the None keyword for the column index, or use slicing for the row index. We’ll learn more about the None keyword later.
You can use slicing, lists of indices, and negative indexing just like we did with 1d arrays.
Once you know how to index a 2d array, modifying its elements is fairly straight-forward. You can replace the 1st element with -1.
You can replace the 2nd row with the 3rd row.
And you can even insert 0s on the diagonal.
Higher dimensional arrays follow the same square bracket notation and indexing pattern, just with more commas.