Unit 5 · Advanced Topics
Introduction to NumPy
NumPy is the fundamental package for scientific computing in Python, providing powerful N-dimensional array objects, broadcasting functions, and tools for integrating C/C++ code. It is the backbone of the entire Python data science ecosystem.
Table of Contents
University Definition
NumPy (Numerical Python) is an open-source library that provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays efficiently. It is written in C and optimized for performance.
Why NumPy?
Speed
NumPy operations are 10–100× faster than Python lists because they are implemented in C.
Memory
NumPy arrays consume less memory than Python lists because they store homogeneous data types.
Convenience
Built-in functions for linear algebra, statistics, Fourier transforms, and random number generation.
Ecosystem
Pandas, Matplotlib, Scikit-learn, TensorFlow — all depend on NumPy arrays.
Installing & Importing
# Install NumPy (run in terminal/command prompt) pip install numpy # Import in your Python script import numpy as np # Check version print(np.__version__)
Creating NumPy Arrays
1. array() — From Python List
import numpy as np # 1D array arr1 = np.array([1, 2, 3, 4, 5]) print(arr1) # Output: [1 2 3 4 5] # 2D array (matrix) arr2 = np.array([[1, 2, 3], [4, 5, 6]]) print(arr2) # Output: # [[1 2 3] # [4 5 6]]
2. zeros() & ones()
# Array filled with zeros zeros_arr = np.zeros((2, 3)) print(zeros_arr) # Output: # [[0. 0. 0.] # [0. 0. 0.]] # Array filled with ones ones_arr = np.ones((3,)) print(ones_arr) # Output: [1. 1. 1.]
3. arange() & linspace()
# arange: evenly spaced values (like range but for arrays) arr = np.arange(0, 10, 2) print(arr) # Output: [0 2 4 6 8] # linspace: evenly spaced numbers over a range arr2 = np.linspace(0, 1, 5) print(arr2) # Output: [0. 0.25 0.5 0.75 1. ]
4. Other Creation Functions
# Full array with a specific value full_arr = np.full((2, 3), 7) print(full_arr) # Output: [[7 7 7] [7 7 7]] # Identity matrix eye_arr = np.eye(3) print(eye_arr) # Output: # [[1. 0. 0.] # [0. 1. 0.] # [0. 0. 1.]] # Random array rand_arr = np.random.rand(2, 3) print(rand_arr) # Output: 2x3 array with random values between 0 and 1
Array Attributes
arr = np.array([[1, 2, 3], [4, 5, 6]]) print(arr.shape) # (2, 3) — 2 rows, 3 columns print(arr.ndim) # 2 — number of dimensions print(arr.dtype) # int32 — data type of elements print(arr.size) # 6 — total number of elements print(arr.nbytes) # 24 — total bytes consumed
| Attribute | Description | Example Output |
|---|---|---|
| shape | Dimensions as tuple | (2, 3) |
| ndim | Number of dimensions | 2 |
| dtype | Data type of elements | int32 |
| size | Total elements count | 6 |
Indexing & Slicing
arr = np.array([10, 20, 30, 40, 50]) # Indexing print(arr[0]) # 10 (first element) print(arr[-1]) # 50 (last element) # Slicing print(arr[1:4]) # [20 30 40] print(arr[::2]) # [10 30 50] — every 2nd element # 2D slicing m = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(m[0, :]) # [1 2 3] — first row print(m[:, 1]) # [2 5 8] — second column print(m[1:, 0:2]) # [[4 5] [7 8]] — sub-matrix
Array Operations
a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) # Element-wise operations print(a + b) # [5 7 9] print(a - b) # [-3 -3 -3] print(a * b) # [4 10 18] print(a / b) # [0.25 0.4 0.5] print(a ** 2) # [1 4 9] # Mathematical functions print(np.sqrt(a)) # [1. 1.414 1.732] print(np.sum(a)) # 6 print(np.mean(a)) # 2.0 print(np.max(a)) # 3 print(np.min(a)) # 1 # Matrix multiplication m1 = np.array([[1, 2], [3, 4]]) m2 = np.array([[5, 6], [7, 8]]) print(np.dot(m1, m2)) # Output: [[19 22] [43 50]]
Broadcasting Basics
University Definition
Broadcasting is NumPy's way of performing operations on arrays of different shapes without explicit looping or copying data. NumPy automatically expands the smaller array across the larger array to make their shapes compatible.
# Scalar + Array (broadcasting) arr = np.array([1, 2, 3]) print(arr + 10) # Output: [11 12 13] # 1D + 2D (broadcasting along rows) matrix = np.array([[1, 2, 3], [4, 5, 6]]) row = np.array([10, 20, 30]) print(matrix + row) # Output: # [[11 22 33] # [14 25 36]]
University Exam Tip
University exams often ask: "What is NumPy? List its advantages", "Differentiate between NumPy array and Python list", or "Explain broadcasting with example". Include code examples with output and a comparison table for full marks.
NumPy Array vs Python List
| Feature | NumPy Array | Python List |
|---|---|---|
| Speed | Very fast (C backend) | Slower (interpreted) |
| Memory | Less memory | More memory |
| Data Type | Homogeneous | Heterogeneous |
| Operations | Element-wise (vectorized) | Requires loops |
| Built-in Functions | sum, mean, dot, etc. | len, sum only |
Key Points
NumPy provides the ndarray object — the core data structure for numerical computing.
Use np.array(), np.zeros(), np.ones(), np.arange(), np.linspace() to create arrays.
shape, ndim, dtype, size are key array attributes.
Broadcasting allows operations on arrays of different shapes without explicit loops.
NumPy arrays are faster and more memory-efficient than Python lists.
import numpy as np is the standard convention.
Practice Questions
- Create a 3×3 identity matrix and print its shape, dtype, and ndim.
- Difference between
np.arange()andnp.linspace()with examples. - Perform element-wise multiplication of two 1D arrays and compute the dot product.
- Explain broadcasting with a 2D and 1D array example.
- Write 5 differences between NumPy array and Python list.
Summary
NumPy is indispensable for scientific computing and data science in Python. It provides fast, memory-efficient arrays, powerful mathematical functions, and broadcasting capabilities. Master array creation, attributes, indexing, slicing, and operations for exams and data analysis work.