Learn Fast Numerical Computing with Python
Introduction
Imagine you have a list of numbers: test scores, temperatures, steps you walked each day, or even pixels in a picture. Sometimes you want to do math with all those numbers at once—quickly and easily. NumPy gives Python superpowers for working with numbers. Its main tool is the array: a fast, flexible container for numbers that makes math simple and fast.
What is NumPy?
NumPy is a Python library that helps you:
- Store lots of numbers efficiently (less memory).
- Do math on whole groups of numbers at once.
- Work with 1D lists, 2D tables, and even 3D data (like images).
Why use NumPy arrays instead of plain Python lists?
- Speed: Arrays are optimized and run faster for large data.
- Simplicity: You can add, subtract, multiply, or compare all elements at once.
- Tools: Handy functions like mean, sum, max, reshape, and more.
Getting Ready
Install (in a terminal or command prompt):
pip install numpyImport in Python:
import numpy as npStep-by-Step: Working with NumPy Arrays
- Create an array — From a Python list. From built-in NumPy creators like zeros, ones, arange, linspace.
- Check array info — shape: the size (like how many rows and columns). size: total number of items. dtype: the type of numbers (int, float, etc.).
- Pick elements (indexing) and slices — parts of the array.
- Do math with arrays — add, subtract, multiply, comparisons.
- Use simple stats — mean, max, min, sum.
- Try 2D arrays — like a small spreadsheet.
Python Code Examples
Example 1: Creating Arrays and Checking Their Info
# Import NumPy
import numpy as np
# Create an array from a Python list
heights_list = [150, 155, 160, 165] # centimeters
heights = np.array(heights_list)
print("heights:", heights) # [150 155 160 165]
print("dtype:", heights.dtype) # int64 (or int32 depending on your computer)
print("shape:", heights.shape) # (4,) means 1D with 4 items
print("size:", heights.size) # 4
# Quick ways to create arrays
zeros = np.zeros(5, dtype=int) # [0 0 0 0 0]
ones = np.ones(3) # [1. 1. 1.] (float by default)
count_by_twos = np.arange(1, 10, 2) # [1 3 5 7 9] start=1, stop=10, step=2
between_0_and_1 = np.linspace(0, 1, 5) # 5 evenly spaced numbers between 0 and 1
print("zeros:", zeros)
print("ones:", ones)
print("count_by_twos:", count_by_twos)
print("between_0_and_1:", between_0_and_1)Example 2: Indexing and Slicing (1D and 2D)
import numpy as np
# 1D array: test scores
scores = np.array([72, 85, 90, 67, 88, 95])
# Indexing (pick one item)
print("First score:", scores[0]) # 72
print("Last score:", scores[-1]) # 95
# Slicing (pick a range) - up to but not including the end index
print("Scores 2 to 4:", scores[1:4]) # [85 90 67]
# Change a slice (sets multiple values at once!)
scores[0:3] = 100
print("After bonus:", scores) # [100 100 100 67 88 95]
# 2D array: like a small table (rows x columns)
grid = np.array([
[1, 2, 3], # row 0
[4, 5, 6] # row 1
])
print("grid shape:", grid.shape) # (2, 3) → 2 rows, 3 columns
print("Item at row 0, col 1:", grid[0, 1]) # 2
# Take a whole column or row
print("First column:", grid[:, 0]) # [1 4]
print("Second row:", grid[1, :]) # [4 5 6]Example 3: Doing Math with Arrays (Whole-Array Operations)
import numpy as np
# Example 1: Temperature conversion (Celsius → Fahrenheit)
temps_c = np.array([20.0, 25.0, 30.0, 18.0])
temps_f = temps_c * 9/5 + 32 # This applies to every element automatically
print("Temps in F:", temps_f) # [68. 77. 86. 64.]
# Example 2: Adding arrays element-by-element
scores = np.array([70, 80, 90, 85])
bonus = np.array([ 5, 10, 0, -3])
new_scores = scores + bonus # [75 90 90 82]
print("New scores:", new_scores)
# Example 3: Quick stats
print("Average score:", scores.mean()) # mean
print("Highest score:", scores.max())
print("Lowest score:", scores.min())
print("Total points:", scores.sum())
# Example 4: Find values that match a condition (boolean mask)
hot_days_mask = temps_c > 25 # [False False True False]
print("Hot day mask:", hot_days_mask)
print("Temps > 25C:", temps_c[hot_days_mask]) # [30.]Note:
- Array math works element-by-element. No loops needed for simple operations!
- Adding a number to an array adds it to every element (called broadcasting).
- Example:
np.array([1, 2, 3]) + 10→[11, 12, 13]
- Example:
Practical Exercise: Weather Helper 🌡️
Goal: Use NumPy to analyze a week of temperatures.
Tasks:
- Create a NumPy array of 7 daily temperatures in Celsius:
[28, 31, 26, 29, 33, 27, 30] - Convert them to Fahrenheit.
- Find the average temperature in Celsius.
- Print only the days that were hotter than 30C.
- Bonus: Replace any temperature below 28C with 28C (as if we corrected a sensor).
Starter code (fill in the blanks):
import numpy as np
temps_c = np.array([28, 31, 26, 29, 33, 27, 30])
# 1) Convert to Fahrenheit: F = C * 9/5 + 32
temps_f = ______________________________
print("Temps in F:", temps_f)
# 2) Average temperature in Celsius
avg_c = ________________________________
print("Average C:", avg_c)
# 3) Days hotter than 30C
hot_mask = _____________________________ # condition like temps_c > 30
print("Hot days (C):", temps_c[hot_mask])
# 4) Bonus: Set any temp < 28C to 28C
temps_fixed = temps_c.copy()
temps_fixed[__________________________] = 28
print("Fixed temps (C):", temps_fixed)Common Tips and Watch-Outs
- Arrays vs lists:
- Python list + list joins them together:
[1, 2] + [3, 4]→[1, 2, 3, 4] - NumPy array + array adds numbers:
np.array([1, 2]) + np.array([3, 4])→[4, 6]
- Python list + list joins them together:
- Shapes must match for element-by-element math:
np.array([1, 2, 3]) + np.array([4, 5])will cause an error (different lengths).
- Dtypes (number types) matter:
- Mixing ints and floats can change dtype to float. That's okay—just be aware.
Recap
- NumPy arrays are like super-powered lists for numbers.
- You can create arrays, check their shape/size, and pick items easily.
- You can do math on the whole array at once (fast and simple).
- Useful functions: mean, sum, max, min, and more.
- Arrays make real-world tasks (like analyzing temperatures or scores) quick and fun.
You're ready to use NumPy arrays in your projects—great job!