NumPy: The Power of Array Operations
After completing this topic, you will be able to:
Explain what NumPy's ndarray is, understand its advantages compared to lists, and perform basic operations.
What is NumPy?
NumPy is a library in Python for fast processing of large numerical datasets.
import numpy as np
# List -> ndarrayarr = np.array([1, 2, 3, 4, 5])print(arr) # [1 2 3 4 5]print(type(arr)) # <class 'numpy.ndarray'>np is the conventional abbreviation for NumPy.
Why NumPy instead of Lists?
Speed Difference
import numpy as np
# Multiply each of 1 million elements by 2
# Pure Python listpy_list = list(range(1_000_000))result = [x * 2 for x in py_list] # Slow
# NumPynp_arr = np.arange(1_000_000)result = np_arr * 2 # Fast (10 to 100 times faster)NumPy is internally written in C and stores data of the same type in contiguous memory. Python lists have each element as an independent Python object, but ndarrays have memory located next to each other, which is beneficial for the CPU cache.
Vectorized Operations
import numpy as np
a = np.array([1, 2, 3])b = np.array([4, 5, 6])
# Element-wise operations β without loopsprint(a + b) # [5 7 9]print(a * b) # [4 10 18]print(a ** 2) # [1 4 9]print(a > 2) # [False False True]In a list, you would have to use a for loop. NumPy allows you to do it in one line.
Creating Arrays
import numpy as np
# Create directlya = np.array([1, 2, 3])
# Array filled with zeroszeros = np.zeros(5) # [0. 0. 0. 0. 0.]
# Array filled with onesones = np.ones(3) # [1. 1. 1.]
# Sequential numbersseq = np.arange(0, 10, 2) # [0 2 4 6 8]
# Equally spaced numberslin = np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1. ]Multi-dimensional Arrays
import numpy as np
# 2-dimensional array (matrix)matrix = np.array([ [1, 2, 3], [4, 5, 6]])print(matrix.shape) # (2, 3) β 2 rows, 3 columnsprint(matrix[0, 1]) # 2 β row 0, column 1print(matrix[:, 0]) # [1 4] β all rows, column 0
# 3-dimensional arrays are also possiblecube = np.zeros((2, 3, 4))print(cube.shape) # (2, 3, 4)shape tells you the size of the array as a tuple. In data analysis, image processing, and machine learning, you will often check the shape.
Common Operations
import numpy as np
arr = np.array([3, 1, 4, 1, 5, 9, 2, 6])
print(arr.sum()) # 31print(arr.mean()) # 3.875print(arr.std()) # 2.588...print(arr.min()) # 1print(arr.max()) # 9print(arr.argmax()) # 5 (index of the maximum value)
# Sortingprint(np.sort(arr)) # [1 1 2 3 4 5 6 9]
# Conditional filteringprint(arr[arr > 3]) # [4 5 9 6]
# Reshape β change shapereshaped = arr.reshape(2, 4)print(reshaped)# [[3 1 4 1]# [5 9 2 6]]Broadcasting
Arrays of different sizes can also perform operations.
import numpy as np
matrix = np.array([ [1, 2, 3], [4, 5, 6]])
# Add [10, 20, 30] to each rowrow = np.array([10, 20, 30])print(matrix + row)# [[11 22 33]# [14 25 36]]NumPy automatically expands row to 2 rows and performs the operation. This is called broadcasting. You don't need to explicitly use loops.