Data Foundations: numpy & pandas
Creating and Indexing Arrays
There are several ways to make arrays. The most common:
import numpy as np
a = np.array([1, 2, 3]) # from a list
b = np.arange(0, 10, 2) # like range: [0 2 4 6 8]
z = np.zeros(4) # [0. 0. 0. 0.]
o = np.ones((2, 3)) # a 2x3 grid of onesEvery array has a dtype (the type of its elements) and a shape (its size along each dimension):
a = np.array([1, 2, 3])
print(a.dtype) # int64
print(a.shape) # (3,) one dimension, length 3
grid = np.array([[1, 2, 3], [4, 5, 6]])
print(grid.shape) # (2, 3) 2 rows, 3 columnsIndexing and slicing work like lists, and start at 0:
a = np.array([10, 20, 30, 40, 50])
print(a[0]) # 10
print(a[-1]) # 50
print(a[1:4]) # [20 30 40] start included, stop excludedFor a 2D array, index with grid[row, col]:
print(grid[0, 2]) # 3 (row 0, column 2)
print(grid[1]) # [4 5 6] (the whole second row)Your turn
Using numpy: build steps = np.arange(0, 10, 2) (the even numbers 0..8). Save its shape into shp. Then slice the middle three values (indexes 1, 2, 3) into mid.
Lesson complete. Nice work.
Code · runs in your browser
Output
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.