Welcome to Module 8, @name! Darwin here with Data Science - the science of data! 📊🐍
Safari Analogy: Data Science is like the Safari analytics system - you collect data about animals, analyze population trends, visualize results, and make decisions based on them! 🦁📈
NumPy (Numerical Python) is the core library for numerical computing. All other DS libraries (Pandas, Scikit-learn) are built on top of it!
1pip install numpy1import numpy as np
2
3# From a list
4arr = np.array([1, 2, 3, 4, 5])
5print(arr) # [1 2 3 4 5]
6
7# 2D array - matrix
8matrix = np.array([
9 [1, 2, 3],
10 [4, 5, 6],
11 [7, 8, 9]
12])
13
14# Special arrays
15zeros = np.zeros((3, 4)) # 3x4 matrix of zeros
16ones = np.ones((2, 3)) # 2x3 matrix of ones
17identity = np.eye(3) # 3x3 identity matrix
18range_arr = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
19linspace = np.linspace(0, 1, 5) # [0, 0.25, 0.5, 0.75, 1]
20random_arr = np.random.rand(3, 3) # Random 3x3 matrix1arr = np.array([[1, 2, 3], [4, 5, 6]])
2
3print(arr.shape) # (2, 3) - dimensions
4print(arr.ndim) # 2 - number of dimensions
5print(arr.size) # 6 - number of elements
6print(arr.dtype) # int64 - data type1# Safari data - populations in different reserves
2populations = np.array([120, 450, 85, 200, 330])
3
4# Basic statistics
5print(np.mean(populations)) # 237.0 - mean
6print(np.median(populations)) # 200.0 - median
7print(np.std(populations)) # 135.4 - standard deviation
8print(np.min(populations)) # 85
9print(np.max(populations)) # 450
10print(np.sum(populations)) # 1185
11
12# Vectorized operations (broadcasting)
13growth = populations * 1.1 # 10% growth
14normalized = (populations - np.mean(populations)) / np.std(populations)1arr = np.array([10, 20, 30, 40, 50])
2
3# Indexing
4print(arr[0]) # 10 - first element
5print(arr[-1]) # 50 - last element
6
7# Slicing
8print(arr[1:4]) # [20 30 40]
9print(arr[:3]) # [10 20 30]
10print(arr[::2]) # [10 30 50] - every other
11
12# Boolean indexing - filtering
13endangered = arr[arr < 30] # [10 20]
14
15# 2D indexing
16matrix = np.array([[1,2,3], [4,5,6], [7,8,9]])
17print(matrix[0, 1]) # 2 - row 0, column 1
18print(matrix[:, 0]) # [1 4 7] - entire column 0
19print(matrix[1, :]) # [4 5 6] - entire row 11arr = np.arange(12) # [0, 1, 2, ..., 11]
2
3# Reshape
4matrix = arr.reshape(3, 4) # 3x4 matrix
5flat = matrix.flatten() # Flatten to 1D
6transposed = matrix.T # Transpose1A = np.array([[1, 2], [3, 4]])
2B = np.array([[5, 6], [7, 8]])
3
4# Element-wise operations
5print(A + B) # Addition
6print(A * B) # Element-wise multiplication
7
8# Matrix multiplication
9print(A @ B) # or np.dot(A, B)
10
11# Linear algebra
12print(np.linalg.det(A)) # Determinant
13print(np.linalg.inv(A)) # Inverse matrix
14eigenvalues, eigenvectors = np.linalg.eig(A)