Chapter 1: NumPy Library
1. Why use NumPy?
Python's built-in lists are flexible but slow for large-scale number crunching because each element can be a different object.
NumPy gives you the ndarray, a contiguous block of memory holding numbers of the same type, so operations run close to C-speed and use less memory .
2. Making an Array
| Goal | Function | Quick idea |
|---|---|---|
| Convert an existing list/tuple | np.array([1,2,3]) | "Just wrap it." |
| All zeros / ones | np.zeros((m,n)), np.ones((m,n)) | Shape is a tuple. |
| A sequence of ints | np.arange(start, stop, step) | Like range() but returns an array |
| Evenly spaced floats | np.linspace(start, stop, num) | Useful for plots. |
| Filled with a value | np.full((m,n), value) | "Make me a matrix of 7s." |
| Random integers | np.random.randint(low, high, size) | Quick random data. |
Tip: After creation you can check .dtype (data type) and .shape (dimensions).
3. Indexing & Slicing
1-D arrays
arr[i] or negative indices like arr[-1] for the last item .
2-D arrays
Use row, col: matrix[2, 3] → element in 3rd row, 4th column .
Slices
Work just like Python lists but faster:
arr[:5] # first 5 elements
arr[::2] # every other element
matrix[:, 0] # first column of every row
matrix[1] # second rowSlices are views, not copies-modify the slice and the original array changes.
4. Handy Aggregate Methods
| Task | Method |
|---|---|
| Minimum / Maximum | np.min(a), np.max(a) |
| Sum / Product | np.sum(a), np.prod(a) |
| Average / Median | np.mean(a), np.median(a) |
| Stitch arrays | np.concatenate([a, b]) |
All operate on the whole array by default and finish in C-compiled code for speed .
5. Element-wise Arithmetic
Create arr = np.arange(10) and try:
arr + 5 # add 5 to every element
arr * 2 # double every element
arr ** 3 # cube every elementThe operator is broadcast across every element, so you write math once and NumPy loops in C behind the scenes .
6. Mini-Walkthrough: Linearly Spaced Data & a Plot
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100) # 100 points from 0 to 2π
y = np.sin(x) # element-wise sine
plt.plot(x, y)
plt.title("Sine Wave")
plt.savefig("sine_wave.png") # saves the imageWhat happened?
linspacegave us smooth x-values.- Applying
np.sinhit every entry at once. - Matplotlib drew the curve and saved it as sine_wave.png.
7. Take-away Checklist
- Use NumPy arrays whenever you need fast, homogeneous numerical data.
- Memorize the five core creators:
array,zeros,ones,arange,linspace. - Remember row, col indexing and that slices are views.
- Use built-in aggregates instead of Python loops.
- Let broadcasting handle element-wise math-write it like algebra.
With these fundamentals you can read, modify, and create almost any numerical workflow in Python confidently.