12  NumPy: Numerical Computing

12.1 Introduction to NumPy

NumPy (Numerical Python) is the fundamental package for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays efficiently.

Why Use NumPy?

  • Performance: NumPy operations are much faster than pure Python loops
  • Memory Efficient: Arrays use less memory than Python lists
  • Convenient: Provides many built-in functions for array manipulation
  • Foundation: Many other scientific libraries (pandas, scikit-learn) are built on NumPy

12.2 Installation

If you don’t have NumPy installed, you can install it using pip:

pip install numpy

12.3 Getting Started

First, let’s import NumPy. The convention is to import it as np:

import numpy as np

# Check NumPy version
print(f"NumPy version: {np.__version__}")
NumPy version: 2.2.6

12.4 Creating NumPy Arrays

From Python Lists

The most basic way to create a NumPy array is from a Python list:

# 1D array from a list
arr_1d = np.array([1, 2, 3, 4, 5])
print("1D Array:", arr_1d)
print("Type:", type(arr_1d))

# 2D array from nested lists
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(arr_2d)
1D Array: [1 2 3 4 5]
Type: <class 'numpy.ndarray'>

2D Array:
[[1 2 3]
 [4 5 6]]

Using Built-in Functions

NumPy provides several functions to create arrays:

# Array of zeros
zeros = np.zeros((3, 4))  # 3 rows, 4 columns
print("Zeros array:")
print(zeros)

# Array of ones
ones = np.ones((2, 3))
print("\nOnes array:")
print(ones)

# Array with a range of values
range_arr = np.arange(0, 10, 2)  # start, stop, step
print("\nRange array:", range_arr)

# Array with evenly spaced values
linspace_arr = np.linspace(0, 1, 5)  # start, stop, number of values
print("\nLinspace array:", linspace_arr)

# Identity matrix
identity = np.eye(3)
print("\nIdentity matrix:")
print(identity)

# Array with random values
random_arr = np.random.rand(2, 3)  # 2x3 array with random values [0, 1)
print("\nRandom array:")
print(random_arr)
Zeros array:
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]

Ones array:
[[1. 1. 1.]
 [1. 1. 1.]]

Range array: [0 2 4 6 8]

Linspace array: [0.   0.25 0.5  0.75 1.  ]

Identity matrix:
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

Random array:
[[0.44005852 0.66614678 0.39645334]
 [0.92696921 0.31584463 0.28848532]]

12.5 Array Attributes

NumPy arrays have useful attributes that describe their properties:

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

print("Array:")
print(arr)
print(f"\nShape: {arr.shape}")        # Dimensions (rows, columns)
print(f"Size: {arr.size}")            # Total number of elements
print(f"Dimensions: {arr.ndim}")      # Number of dimensions
print(f"Data type: {arr.dtype}")      # Type of elements
print(f"Item size: {arr.itemsize} bytes")  # Size of each element
Array:
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

Shape: (3, 4)
Size: 12
Dimensions: 2
Data type: int64
Item size: 8 bytes

12.6 Array Indexing and Slicing

Indexing

Access elements using square brackets (0-indexed):

arr_1d = np.array([10, 20, 30, 40, 50])

# Single element
print("First element:", arr_1d[0])
print("Last element:", arr_1d[-1])

# 2D array indexing
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("\n2D Array:")
print(arr_2d)
print("Element at row 1, column 2:", arr_2d[1, 2])  # Returns 6
First element: 10
Last element: 50

2D Array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
Element at row 1, column 2: 6

Slicing

Extract portions of arrays:

arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

# Basic slicing [start:stop:step]
print("Elements 2 to 5:", arr[2:6])
print("Every other element:", arr[::2])
print("First 5 elements:", arr[:5])
print("Last 3 elements:", arr[-3:])

# 2D slicing
arr_2d = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print("\n2D Array:")
print(arr_2d)
print("\nFirst 2 rows, all columns:")
print(arr_2d[:2, :])
print("\nAll rows, columns 1 to 3:")
print(arr_2d[:, 1:3])
Elements 2 to 5: [2 3 4 5]
Every other element: [0 2 4 6 8]
First 5 elements: [0 1 2 3 4]
Last 3 elements: [7 8 9]

2D Array:
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

First 2 rows, all columns:
[[1 2 3 4]
 [5 6 7 8]]

All rows, columns 1 to 3:
[[ 2  3]
 [ 6  7]
 [10 11]]

12.7 Array Operations

Element-wise Operations

NumPy performs operations element-by-element:

a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])

print("Array a:", a)
print("Array b:", b)

# Basic arithmetic
print("\nAddition (a + b):", a + b)
print("Subtraction (a - b):", a - b)
print("Multiplication (a * b):", a * b)
print("Division (a / b):", a / b)
print("Power (a ** 2):", a ** 2)

# Operations with scalars
print("\nScalar multiplication (a * 10):", a * 10)
print("Scalar addition (a + 5):", a + 5)
Array a: [1 2 3 4]
Array b: [10 20 30 40]

Addition (a + b): [11 22 33 44]
Subtraction (a - b): [ -9 -18 -27 -36]
Multiplication (a * b): [ 10  40  90 160]
Division (a / b): [0.1 0.1 0.1 0.1]
Power (a ** 2): [ 1  4  9 16]

Scalar multiplication (a * 10): [10 20 30 40]
Scalar addition (a + 5): [6 7 8 9]

Broadcasting

NumPy can perform operations on arrays of different shapes:

# 2D array
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# 1D array
vector = np.array([10, 20, 30])

print("Matrix:")
print(matrix)
print("\nVector:", vector)

# Broadcasting: vector is added to each row
result = matrix + vector
print("\nMatrix + Vector:")
print(result)
Matrix:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Vector: [10 20 30]

Matrix + Vector:
[[11 22 33]
 [14 25 36]
 [17 28 39]]

12.8 Useful NumPy Functions

Statistical Functions

data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

print("Data:", data)
print(f"\nSum: {np.sum(data)}")
print(f"Mean: {np.mean(data)}")
print(f"Median: {np.median(data)}")
print(f"Standard deviation: {np.std(data):.2f}")
print(f"Minimum: {np.min(data)}")
print(f"Maximum: {np.max(data)}")
print(f"Index of minimum: {np.argmin(data)}")
print(f"Index of maximum: {np.argmax(data)}")
Data: [ 1  2  3  4  5  6  7  8  9 10]

Sum: 55
Mean: 5.5
Median: 5.5
Standard deviation: 2.87
Minimum: 1
Maximum: 10
Index of minimum: 0
Index of maximum: 9

Aggregation Along Axes

For multi-dimensional arrays, you can specify the axis:

matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print("Matrix:")
print(matrix)

print("\nSum of all elements:", np.sum(matrix))
print("Sum along columns (axis=0):", np.sum(matrix, axis=0))
print("Sum along rows (axis=1):", np.sum(matrix, axis=1))

print("\nMean of each column:", np.mean(matrix, axis=0))
print("Mean of each row:", np.mean(matrix, axis=1))
Matrix:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Sum of all elements: 45
Sum along columns (axis=0): [12 15 18]
Sum along rows (axis=1): [ 6 15 24]

Mean of each column: [4. 5. 6.]
Mean of each row: [2. 5. 8.]

Reshaping Arrays

arr = np.arange(12)
print("Original array:", arr)

# Reshape to 2D
reshaped = arr.reshape(3, 4)
print("\nReshaped (3x4):")
print(reshaped)

# Reshape to 3D
reshaped_3d = arr.reshape(2, 3, 2)
print("\nReshaped (2x3x2):")
print(reshaped_3d)

# Flatten back to 1D
flattened = reshaped.flatten()
print("\nFlattened:", flattened)
Original array: [ 0  1  2  3  4  5  6  7  8  9 10 11]

Reshaped (3x4):
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Reshaped (2x3x2):
[[[ 0  1]
  [ 2  3]
  [ 4  5]]

 [[ 6  7]
  [ 8  9]
  [10 11]]]

Flattened: [ 0  1  2  3  4  5  6  7  8  9 10 11]

Stacking Arrays

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Vertical stack (rows)
v_stack = np.vstack((a, b))
print("Vertical stack:")
print(v_stack)

# Horizontal stack (columns)
h_stack = np.hstack((a, b))
print("\nHorizontal stack:")
print(h_stack)
Vertical stack:
[[1 2 3]
 [4 5 6]]

Horizontal stack:
[1 2 3 4 5 6]

12.9 Practical Examples

Example 1: Grade Analysis

# Student grades in 5 subjects
grades = np.array([
    [85, 90, 78, 92, 88],  # Student 1
    [76, 82, 85, 79, 90],  # Student 2
    [92, 95, 89, 94, 91],  # Student 3
    [68, 72, 75, 70, 73]   # Student 4
])

print("Grades array:")
print(grades)

# Calculate average grade per student
student_avg = np.mean(grades, axis=1)
print("\nAverage grade per student:")
for i, avg in enumerate(student_avg, 1):
    print(f"Student {i}: {avg:.2f}")

# Calculate average grade per subject
subject_avg = np.mean(grades, axis=0)
print("\nAverage grade per subject:")
subjects = ['Math', 'Science', 'English', 'History', 'Art']
for subject, avg in zip(subjects, subject_avg):
    print(f"{subject}: {avg:.2f}")

# Find highest and lowest grades
print(f"\nHighest grade: {np.max(grades)}")
print(f"Lowest grade: {np.min(grades)}")
Grades array:
[[85 90 78 92 88]
 [76 82 85 79 90]
 [92 95 89 94 91]
 [68 72 75 70 73]]

Average grade per student:
Student 1: 86.60
Student 2: 82.40
Student 3: 92.20
Student 4: 71.60

Average grade per subject:
Math: 80.25
Science: 84.75
English: 81.75
History: 83.75
Art: 85.50

Highest grade: 95
Lowest grade: 68

Example 2: Temperature Conversion

# Temperatures in Celsius
celsius = np.array([0, 10, 20, 30, 40, 100])

# Convert to Fahrenheit
fahrenheit = (celsius * 9/5) + 32

print("Temperature Conversion:")
print("Celsius    | Fahrenheit")
print("-" * 25)
for c, f in zip(celsius, fahrenheit):
    print(f"{c:7.1f}°C  | {f:7.1f}°F")
Temperature Conversion:
Celsius    | Fahrenheit
-------------------------
    0.0°C  |    32.0°F
   10.0°C  |    50.0°F
   20.0°C  |    68.0°F
   30.0°C  |    86.0°F
   40.0°C  |   104.0°F
  100.0°C  |   212.0°F

Example 3: Simple Data Filtering

# Array of values
values = np.array([12, 45, 23, 67, 34, 89, 56, 78, 90, 21])

print("Original values:", values)

# Boolean indexing
greater_than_50 = values > 50
print("\nValues greater than 50:", values[greater_than_50])

# Multiple conditions
between_30_and_70 = (values >= 30) & (values <= 70)
print("Values between 30 and 70:", values[between_30_and_70])

# Replace values
values_copy = values.copy()
values_copy[values_copy > 50] = 50  # Cap values at 50
print("Values capped at 50:", values_copy)
Original values: [12 45 23 67 34 89 56 78 90 21]

Values greater than 50: [67 89 56 78 90]
Values between 30 and 70: [45 67 34 56]
Values capped at 50: [12 45 23 50 34 50 50 50 50 21]

12.10 Key Takeaways

  1. NumPy arrays are faster and more efficient than Python lists for numerical operations
  2. Use np.array() to create arrays from lists, or built-in functions like np.zeros(), np.ones(), np.arange()
  3. Indexing works like lists, but with additional dimensions: arr[row, col]
  4. Operations are element-wise by default
  5. NumPy provides many built-in mathematical and statistical functions
  6. Broadcasting allows operations on arrays of different shapes
  7. Use axis parameter to perform operations along specific dimensions

12.11 Next Steps

Now that you understand the basics of NumPy, you can:

  • Explore more advanced array manipulation techniques
  • Learn about linear algebra operations (np.dot(), np.linalg module)
  • Study random number generation (np.random module)
  • Move on to pandas for data analysis (built on NumPy)
  • Explore matplotlib for data visualization (works great with NumPy)

12.12 Additional Resources

Happy coding with NumPy!