Creating arrays
From a list
Python
import numpy as np
a = np.array([3, 1, 4, 1, 5])
b = np.array([[1, 2, 3],
[4, 5, 6]]) # a 2D array from a list of lists
print(a)
print(b)Built-in constructors
Python
import numpy as np
print(np.zeros(5)) # five 0.0s
print(np.ones((2, 3))) # 2 rows, 3 columns of 1.0
print(np.full((2, 2), 7)) # filled with 7
print(np.arange(0, 20, 5)) # like range(): 0, 5, 10, 15
print(np.linspace(0, 1, 5)) # 5 evenly spaced values from 0 to 1
print(np.eye(3)) # identity matrixarange steps by a fixed amount; linspace gives an exact number of points, including the end.
Shape, size, dimensions and type
Python
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]])
print("shape:", m.shape) # (rows, columns)
print("ndim: ", m.ndim) # number of dimensions
print("size: ", m.size) # total elements
print("dtype:", m.dtype) # element typedtype: one type for every element
Python
import numpy as np
print(np.array([1, 2, 3]).dtype)
print(np.array([1.5, 2, 3]).dtype) # one float makes them all float
print(np.array([1, 2, 3], dtype=float))
print(np.array([1.9, 2.7]).astype(int)) # astype converts (and truncates)Random arrays
Python
import numpy as np
rng = np.random.default_rng(seed=42) # a seed makes results repeatable
print(rng.integers(1, 7, size=10)) # ten dice rolls
print(rng.random(3)) # three floats in [0, 1)
print(rng.normal(170, 8, size=4).round(1)) # heights: mean 170, sd 8Finished this lesson?Mark it complete to earn +20 XP and move your progress on.