NumPy and Scientific Computing¶
By the end of this lesson you'll be able to:
- Create NumPy arrays with
np.array(),np.zeros(),np.ones(), andnp.linspace() - Perform element-wise math and understand broadcasting
- Slice and index NumPy arrays, including 2-D arrays
- Compute mean, standard deviation, max, and argmax on arrays
- Combine NumPy with matplotlib to plot a sine wave
Python lists are flexible, but slow for large numerical datasets. NumPy (Numerical Python) provides an array type that is 10–100× faster because it stores values compactly and performs operations in optimized C code.
Welcome to Chapter 33!
NumPy is the engine under almost every data science and machine learning library in Python.
Learn it once and you'll use it in every science project for the rest of your coding career.
Let's dive in! Let's code it together!
Importing NumPy¶
Import NumPy with the standard alias np:
1 | |
Creating Arrays with np.array()¶
A NumPy array (ndarray) is like a Python list, but:
- All items must be the same type (usually float64 or int64)
- Math operations work element-by-element automatically
- It can be multi-dimensional (2-D, 3-D, etc.)
Convert a Python list to an array:
1 2 3 4 | |
Element-Wise Math and Broadcasting¶
The big difference between lists and arrays: math operators work element-by-element.
1 2 3 4 | |
Adding a single number to every element is called broadcasting — NumPy "broadcasts" the scalar value across the whole array automatically, with no loop needed.
Two arrays of the same shape can be combined element-by-element:
1 2 | |
What Do You Think Will Happen?
The code below applies element-wise math to an array.
Before you run it, predict: what will temps_f look like after the formula?
Make your guess — then run it!
Creating Arrays Automatically¶
NumPy provides functions for common array creation patterns:
| Function | Creates |
|---|---|
np.zeros(n) |
Array of n zeros |
np.ones(n) |
Array of n ones |
np.arange(start, stop, step) |
Like range() but returns an array |
np.linspace(start, stop, num) |
Evenly spaced values between start and stop |
np.random.rand(n) |
n random values between 0 and 1 |
np.linspace() is especially useful for math and plotting — it generates exactly num evenly spaced points:
1 2 | |
Slicing and Indexing¶
NumPy arrays use the same [start:stop:step] slicing syntax as Python lists:
1 2 3 4 | |
2-D Arrays — Rows and Columns¶
A 2-D array is like a spreadsheet table — it has rows and columns. Create one by passing a list of lists:
1 2 3 4 5 6 7 8 | |
The index matrix[row, col] selects a specific cell.
matrix[row, :] selects a whole row; matrix[:, col] selects a whole column.
Reshaping Arrays¶
array.reshape(rows, cols) rearranges an array into a different shape without changing the data.
The total number of elements must stay the same.
1 2 3 | |
Statistical Functions¶
NumPy has fast built-in statistics:
| Function | Returns |
|---|---|
a.mean() |
Average |
a.std() |
Standard deviation |
a.min() / a.max() |
Minimum / maximum value |
a.sum() |
Sum of all elements |
a.argmax() |
Index of the maximum value |
a.argmin() |
Index of the minimum value |
argmax() and argmin() are especially useful when you want to know where in an array the maximum or minimum occurs — not just what the value is.
Plotting a Sine Wave with NumPy and matplotlib¶
This is where NumPy and matplotlib combine: use np.linspace() to generate evenly spaced x values, apply np.sin() to get y values, then plot.
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
np.sin(), np.cos(), np.exp(), and np.sqrt() all work on entire arrays — no loop needed.
Learning Check¶
Your Turn — Find the Hottest Day
The code below has temperature data for a week, but the line that finds the hottest day is missing!
Add one line using argmax() to find and print which day of the week had the highest temperature.
Experiments¶
Try these changes. Predict what will happen first, then run it to check!
-
Create a 4×4 identity matrix using
np.eye(4)— a square matrix with 1s on the diagonal. You'll know it worked when you see 1s along the diagonal and 0s everywhere else. -
Compute the dot product of two arrays using
np.dot([1,2,3], [4,5,6]). You'll know it worked when you get32(1×4 + 2×5 + 3×6 = 32). -
Generate 5 random integers between 1 and 100 using
np.random.randint(1, 101, 5). Find the mean. You'll know it worked when you get a different set of numbers each run with a mean between 1 and 100. -
Use
np.where(temps > 25, "Hot", "Cool")on the temperature array to label each day. You'll know it worked when you see a string array like["Cool", "Cool", "Hot", ...]. -
Create a 3×3 matrix and use
matrix.Tto transpose it (rows become columns). You'll know it worked when the rows and columns are swapped.
Scientific Python Pioneer!
NumPy is the foundation of the entire scientific Python ecosystem — pandas, scikit-learn, TensorFlow, and PyTorch all use NumPy arrays under the hood.
Mastering it puts you at the starting line of data science and AI. Let's keep coding!