NumPy is Python's foundational library for numeric computing. Its core object, the array, is Python's equivalent of an R vector or matrix — fast, memory-efficient, and fully vectorised.
Installing and Importing NumPy
R Code
pip install numpy # then, in your script: import numpy as np
Creating an Array
R Code
ages = np.array([20, 22, 19, 25]) print(ages) print(type(ages)) # other common ways to create arrays print(np.arange(0, 10, 2)) # like range(), but returns an array print(np.linspace(0, 1, 5)) # 5 evenly spaced values from 0 to 1 print(np.zeros(3)) print(np.ones(3))
Output
[20 22 19 25] <class 'numpy.ndarray'> [0 2 4 6 8] [0. 0.25 0.5 0.75 1. ] [0. 0. 0.] [1. 1. 1.]
Vectorised Arithmetic
Just like R, NumPy applies an operation to every element at once, with no explicit loop.
R Code
scores = np.array([70, 85, 90, 60]) print(scores + 5) print(scores / 100 * 20) print(scores > 75)
Output
[75 90 95 65] [14. 17. 18. 12.] [False True True False]
⚠ Common Mistake
A plain Python list does not support this: [70,85,90] + 5 raises a TypeError. Vectorised arithmetic like this only works on NumPy arrays (or pandas Series), not built-in lists.Indexing, Slicing, and Boolean Masking
R Code
arr = np.array([10, 20, 30, 40, 50]) print(arr[1]) # single element print(arr[1:4]) # slice print(arr[arr > 25]) # boolean masking - only values greater than 25
Output
20 [20 30 40] [30 40 50]
2-D Arrays (Matrices)
R Code
matrix = np.array([[1,2,3], [4,5,6]]) print(matrix.shape) # (rows, columns) print(matrix[0, 1]) # row 0, column 1 print(matrix[:, 1]) # entire second column print(matrix.T) # transpose
Output
(2, 3) 2 [2 5] [[1 4] [2 5] [3 6]]
Useful Array Functions
R Code
data = np.array([23, 9, 45, 12, 9, 30]) print(np.mean(data)) print(np.median(data)) print(np.std(data)) print(np.sort(data)) print(np.unique(data))
Output
21.33333333333333 17.5 13.079... [ 9 9 12 23 30 45] [ 9 12 23 30 45]
Advanced: Matrix Multiplication and Linear Algebra
🚀 Advanced Example
NumPy\'s linear algebra module can solve systems of equations directly, just like R\'s solve().R Code
A = np.array([[2,1], [1,3]]) b = np.array([5, 10]) print(A @ A) # @ is the matrix multiplication operator print(np.linalg.solve(A, b)) # solve 2x + y = 5, x + 3y = 10
Output
[[5 5] [5 10]] [1. 3.]
Key Points
- A NumPy array is Python\'s fast, vectorised equivalent of R\'s vector/matrix.
- Arithmetic and comparisons apply element-by-element automatically - plain Python lists do not support this.
- Boolean masking (arr[arr > value]) is the standard way to filter an array.
- The @ operator performs true matrix multiplication; np.linalg.solve() solves linear systems.