Share on:

Python NumPy For Your Grandma | Section 5 | Challenges
December 29, 2019

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])

Enjoyed this article? Show your support and buy some GormAnalysis merch.
comments powered by Disqus