Contents

Python NumPy For Your Grandma | Section 5 | Challenges

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

Section 5.1 | New Column From Others

Code

## Given a 10x2 array of floats where the 1st column contains some nan values,
## create a 3rd column equal to column 1 where it's not nan and column 2 where it is nan.
## In other words, set column 3 equal to column 1, but fall back on column 2 where column 1 has a missing value.

# Setup
import numpy as np
np.random.seed(123)
foo = np.random.uniform(low = 0.0, high = 1.0, size = (10, 2))
foo[np.random.randint(low = 0, high = 10, size = 5), np.repeat(0, 5)] = np.nan
foo = np.round(foo, 2)

Section 5.2 | Replace N Values Where

Code

# Given a 1d array of integers, identify the first three values < 10 and replace them with 0.

# Setup
import numpy as np
moo = np.array([0, 15, 32, 11, 5, 5, 24, 99, 81, 3, 45, 9, 41])

Section 5.3 | Random Insertions

Code

# Insert 10 random normal values into a 5x5 array of 0s at random locations.

# Setup
import numpy as np
oof = np.zeros(shape = (5, 5))

Section 5.4 | Index Onwards

Code

# Given peanut, a 4x5 array of 0s, and butter, a 5-element array of indices, fill
# the rows of peanut with 1s starting from the column indices given by butter.

# Setup
import numpy as np
peanut = np.zeros(shape = (4, 5))
butter = np.array([3, 0, 4, 1])

Section 5.5 | One-Hot Encoding

Code

# Given an array of integers, one hot encode it into a 2d array.

# Setup
import numpy as np
yoyoyo = np.array([3, 1, 0, 1])