Contents

Python NumPy For Your Grandma | Section 2.4 | Indexing And Modifying Multidimensional Arrays

Contents

Course Contents

  1. Introduction
  2. NumPy Arrays
    2.1 What’s A NumPy Array
    2.2 Creating NumPy Arrays
    2.3 Indexing And Modifying 1-D Arrays
    2.4 Indexing And Modifying Multidimensional Arrays
    2.5 Basic Math
  3. Intermediate Array Stuff
    3.1 Broadcasting
    3.2 newaxis
    3.3 reshape
    3.4 boolean indexing
    3.5 nan
    3.6 infinity
    3.7 random
  4. Common Operations
    4.1 where
    4.2 Math Funcs
    4.3 all and any
    4.4 concatenate
    4.5 Stacking
    4.6 Sorting
    4.7 unique
  5. Challenges

This video covers how to index and modify multidimensional NumPy arrays.

Code

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[0]

# 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[1] = bar[2]

# insert 0s on diagonal
bar[[0, 1, 2], [0, 1, 2]] = [0, 0, 0]

Transcript

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.