Introduction to NumPy ndarrays
In standard Python, lists are containers that store references to items anywhere in memory. While flexible, this adds performance overhead. NumPy (Numerical Python) introduces the ndarray (n-dimensional array), which stores elements of the same type in contiguous memory blocks. This layout enables vectorization—performing calculations directly in compiled C code, speeding up array operations by up to 100x.
16.1 The Basics: Array Creation & Attributes
To use NumPy, we import it (conventionally as np) and cast Python lists into arrays using np.array(). Once created, we can inspect array properties using attributes:
dtype: The data type of the elements (e.g.,int64,float64).size: The total count of elements inside the array.ndim: The number of dimensions or rank of the array (e.g.,1for a 1D array).shape: A tuple showing the dimensions and sizes (e.g.,(5,)for 5 elements in a 1D array).
import numpy as np
# Cast Python list to a 1D NumPy array
a = [10, 20, 30, 40, 50]
arr = np.array(a)
print("Array:", arr)
print("Data Type (dtype):", arr.dtype)
print("Total size:", arr.size)
print("Dimensions (ndim):", arr.ndim)
print("Shape:", arr.shape)
Try Array Inspector: Click "Try It Yourself" to run basic array creation. Inspect memory attributes such as dtype, size, and shape.
Modify values in the comma-separated input list, cast it to a NumPy array, and click on attributes to inspect their values.
16.2 Vector Operations & Broadcasting
In standard Python lists, adding two arrays requires iterating through indices. In NumPy, operations are vectorized: when you add or multiply arrays, the math is applied element-wise automatically. We can visualize this using Euclidean vectors.
import numpy as np
u = np.array([3, 0])
v = np.array([0, 2])
# Vector addition & subtraction
print("u + v =", u + v)
print("u - v =", u - v)
# Scalar stretching (multiplication)
print("2 * u =", 2 * u)
# Hadamard (element-wise) Product
print("u * v =", u * v)
# Dot Product (scalar similarity)
print("np.dot(u, v) =", np.dot(u, v))
# Broadcasting scalar to array
print("u + 10 =", u + 10)
Try Vector Operations: Click "Try It Yourself" to run vector calculations in NumPy. These mathematical operations run in compiled C code and optimize memory usage.
Toggle the operations below to visualize vector additions, subtraction, scalar stretching, Hadamard entrywise multiplication, and broadcasting.
16.3 Universal Functions & Interval Sampling (linspace)
A **universal function** (or *ufunc*) performs element-wise operations on arrays. Examples include mean(), max(), and trigonometric functions like np.sin().
To sample mathematical curves or generate evenly spaced intervals, NumPy provides np.linspace(start, stop, num). Adjusting the sample count (num) defines how detailed the resulting mapping is.
Move the slider to configure the sample size in np.linspace(0, 2*pi, num). Watch how increasing samples yields a smooth, continuous sine wave.
import numpy as np
# Generate 9 evenly spaced samples over the interval -2 to 2
x = np.linspace(-2, 2, 9)
print("x samples:\n", x)
# Generate 100 samples from 0 to 2*pi and calculate sine values
x_sine = np.linspace(0, 2 * np.pi, 100)
y_sine = np.sin(x_sine)
print("\nFirst 5 y values (np.sin(x)):\n", y_sine[:5])
Practice Quiz
Validate your understanding of NumPy dimensions, Euclidean vector calculations, and linspace parameters.