NumPy · Lesson 0.2

Creating arrays

Make arrays of steps, evenly spaced points or a fixed value, and change their type.

1Ranges with arange

np.arange(start, stop, step) counts from start up to, but not including, stop. It's like range(), but gives an array.

import numpy as np

print(np.arange(5))
print(np.arange(2, 11, 2))
print(np.arange(0, 1, 0.25))
NumPy (illustrative numbers)

Practice

Store the even numbers from 10 to 30, including 30, as an array.

import numpy as np

result = ...
NumPy (illustrative numbers)

2Evenly spaced points with linspace

np.linspace(start, stop, n) gives n evenly spaced values and includes both ends. Use it when you know how many points you want rather than the step.

import numpy as np

np.linspace(0, 100, 5)
NumPy (illustrative numbers)

Practice

Store 6 evenly spaced values from 1 to 2, including both ends.

import numpy as np

result = ...
NumPy (illustrative numbers)

3Filled arrays

np.zeros(n), np.ones(n) and np.full(n, value) make arrays where every value is the same. They're handy starting points that you fill in later.

import numpy as np

print(np.zeros(4))
print(np.ones(3))
print(np.full(5, 7))
print(np.zeros((2, 3)))
NumPy (illustrative numbers)

Practice

A team starts each of the 7 days of a week with a budget of 250. Store an array with the budget for each day.

import numpy as np

result = ...
NumPy (illustrative numbers)

4Changing the type with astype

arr.astype(int) turns values into whole numbers by cutting off the decimals, not rounding. Round first with np.round if you want the nearest whole number.

import numpy as np

ratings = np.array([3.7, 4.2, 4.9])
print(ratings.astype(int))
print(np.round(ratings).astype(int))
NumPy (illustrative numbers)

Practice

Round each rating to the nearest whole star and store them as whole numbers.

import numpy as np

ratings = np.array([2.4, 3.5, 4.6, 1.2, 4.95])
result = ...
NumPy (illustrative numbers)

Quick check

What does np.arange(1, 4) give?