Lecture 3
NumPy
Multi-Dimensional Arrays
Creating Arrays
import numpy as np
# Scalar (0-dimensional) array
a = np.array(45)
print(a.ndim, a) # Output: 0 45
# 1D array from a list
b = np.array([1, 2, 3])
print(b.ndim, b) # Output: 1 [1 2 3]
# 1D array from a tuple
c = np.array((1, 2, 3))
print(c.ndim, c) # Output: 1 [1 2 3]
# 2D array from a nested list
d = np.array([[1, 2, 3], [3, 4, 5], [2, 3, 4]])
print(d.ndim, d) # Output: 2 [[1 2 3] [3 4 5] [2 3 4]]
# 5D array with explicit dimensions
e = np.array((1, 2, 3), ndmin=5)
print(e.ndim, e) # Output: 5 [[[[[1 2 3]]]]]
Accessing Array Elements
# Accessing elements in 1D arrays
print(b[0], ', ', b[2]) # Output: 1, 3
print(c[0], ', ', c[1], ', ', c[-1]) # Output: 1, 2, 3
# Accessing elements in 2D arrays
print(d[0, 0], ', ', d[1, 2]) # Output: 1, 5
# Accessing elements in 5D arrays
print(e[0, 0, 0, 0, 2]) # Output: 3
Slicing Arrays
# Slicing a 1D array
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(x[1:5]) # Output: [2 3 4 5]
print(x[4:])
# Output: [5 6 7 8 9 10]
print(x[:4])
# Output: [1 2 3 4]
print(x[-3:-1]) # Output: [8 9]
print(x[1:5:2]) # Output: [2 4]
print(x[::2])
# Output: [1 3 5 7 9]
# Slicing a 2D array
x = np.array([[1, 2, 3, 5], [3, 4, 5, 9], [2, 3, 4, 12], [4, 2, 3, 1]])
print(x[1, 1:4]) # Output: [4 5 9]
print(x[0:2, 2:4]) # Output: [[3 5] [5 9]]
print(x[1:3, 1:3]) # Output: [[4 5] [3 4]]
Data Type Conversion
# Creating arrays with specific data types
x = np.array([1.2, 2.4, 3.5], dtype='f8')
print(x.dtype, x) # Output: float64 [1.2 2.4 3.5]
# Converting data types
y = x.astype('i4')
print(y.dtype, y) # Output: int32 [1 2 3]
# Creating arrays with integer types
x = np.array([1.2, 2.4, 3.5], dtype='i4')
print(x.dtype, x) # Output: int32 [1 2 3]
# Creating arrays with smaller integer types
x = np.array([1.2, 2.4, 3.5], dtype='i1')
print(x.dtype, x) # Output: int8 [1 2 3]
# Converting string representations to numerical types
x = np.array(["1.2", "2.4", "3.5"], dtype='f8')
print(x.dtype, x) # Output: float64 [1.2 2.4 3.5]
Copy vs. View
# Creating a copy of an array
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = x.copy()
x[1] = 12
print(y) # Output: [1 2 3 4 5 6 7 8 9 10]
# Creating a view of an array
y = x.view()
x[1] = 12
print(y) # Output: [1 12 3 4 5 6 7 8 9 10]
# Modifying the view affects the original array
y[1] = 15
print(x) # Output: [1 15 3 4 5 6 7 8 9 10]
# Checking if an array owns its data
print(x.base, y.base) # Output: None [1 15 3 4 5 6 7 8 9 10]
Reshaping Arrays
# Reshaping a 2D array
x = np.array([[1, 2, 3, 5], [3, 4, 5, 9], [2, 3, 4, 12], [4, 2, 3, 1]])
print(x.shape) # Output: (4, 4)
# Reshaping to 2x8
y = x.reshape(2, 8)
print(y) # Output: [[1 2 3 5 3 4 5 9] [2 3 4 12 4 2 3 1]]
# Flattening the array
y = x.reshape(-1)
print(y) # Output: [1 2 3 5 3 4 5 9 2 3 4 12 4 2 3 1]
# Checking if the reshaped array is a view
print(y.base) # Output: [[1 2 3 5] [3 4 5 9] [2 3 4 12] [4 2 3 1]]
Iterators
# Iterating over a 1D array
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
for i in x:
print(i) # Output: 1 2 3 4 5 6 7 8 9 10
# Iterating over a 2D array
x = np.array([[1, 2, 3, 5], [3, 4, 5, 9], [2, 3, 4, 12], [4, 2, 3, 1]])
for i in x:
print(i) # Output: [1 2 3 5] [3 4 5 9] [2 3 4 12] [4 2 3 1]
# Iterating over individual elements in a 2D array
for i in x:
for j in i:
print(j) # Output: 1 2 3 5 3 4 5 9 2 3 4 12 4 2 3 1
# Using np.nditer for efficient iteration
for i in np.nditer(x):
print(i) # Output: 1 2 3 5 3 4 5 9 2 3 4 12 4 2 3 1
# Using np.ndenumerate to get indices and values
for idx, i in np.ndenumerate(x):
print(idx, i) # Output: (0, 0) 1, (0, 1) 2, ..., (3, 3) 1
Joining Arrays
# Joining arrays along rows (axis=0)
x = np.array([[1, 1, 1], [2, 2, 2]])
y = np.array([[3, 3, 3], [4, 4, 4]])
z = np.concatenate((x, y))
print(z.shape, z) # Output: (4, 3) [[1 1 1] [2 2 2] [3 3 3] [4 4 4]]
# Joining arrays along columns (axis=1)
z = np.concatenate((x, y), axis=1)
print(z.shape, z) # Output: (2, 6) [[1 1 1 3 3 3] [2 2 2 4 4 4]]
# Stacking arrays along a new axis
z = np.stack((x, y))
print(z.shape, z) # Output: (2, 2, 3) [[[1 1 1] [2 2 2]] [[3 3 3] [4 4 4]]]
# Vertical and horizontal stacking
z = np.vstack((x, y)) # Equivalent to concatenate(axis=0)
print(z.shape, z) # Output: (4, 3) [[1 1 1] [2 2 2] [3 3 3] [4 4 4]]
z = np.hstack((x, y)) # Equivalent to concatenate(axis=1)
print(z.shape, z) # Output: (2, 6) [[1 1 1 3 3 3] [2 2 2 4 4 4]]
# Stacking along depth (3rd axis)
z = np.dstack((x, y))
print(z.shape, z) # Output: (2, 3, 2) [[[1 3] [1 3] [1 3]] [[2 4] [2 4] [2 4]]]
Splitting Arrays
# Splitting a 1D array into 3 parts
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array_split(x, 3)
print(y) # Output: [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]
# Splitting a 2D array along rows
x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17,
18]])
y = np.array_split(x, 3, axis=0)
print(y) # Output: [array([[1, 2, 3], [4, 5, 6]]), array([[7, 8, 9], [10, 11, 12]]),
array([[13, 14, 15], [16, 17, 18]])]
# Splitting a 2D array along columns
y = np.array_split(x, 3, axis=1)
print(y) # Output: [array([[1], [4], [7], [10], [13], [16]]), array([[2], [5], [8],
[11], [14], [17]]), array([[3], [6], [9], [12], [15], [18]])]
# Using vsplit and hsplit
y = np.vsplit(x, 3) # Equivalent to array_split(axis=0)
print(y) # Output: [array([[1, 2, 3], [4, 5, 6]]), array([[7, 8, 9], [10, 11, 12]]),
array([[13, 14, 15], [16, 17, 18]])]
y = np.hsplit(x, 3) # Equivalent to array_split(axis=1)
print(y) # Output: [array([[1], [4], [7], [10], [13], [16]]), array([[2], [5], [8],
[11], [14], [17]]), array([[3], [6], [9], [12], [15], [18]])]
Searching, Sorting, and Filtering
# Searching for elements
x = np.array([11, 31, 87, 19, 23, 43])
y = np.where(x == 19)
print(y) # Output: (array([3]),)
# Sorting an array
y = np.sort(x)
print(y) # Output: [11 19 23 31 43 87]
# Filtering elements using a boolean mask
s = [True, False, False, False, True, True]
y = x[s]
print(y) # Output: [11 23 43]
NumPy Random Module
Basics
import numpy as np
from numpy import random
# Generating random floats
x = random.rand()
print(x) # Output: Random float between 0 and 1
# Generating random integers
x = random.randint(100)
print(x) # Output: Random integer between 0 and 99
x = random.randint(100, size=5)
print(x) # Output: Array of 5 random integers between 0 and 99
x = random.randint(100, size=(5, 3))
print(x) # Output: 5x3 array of random integers between 0 and 99
# Generating random floats in a specific shape
x = random.rand(5)
print(x) # Output: Array of 5 random floats
x = random.rand(5, 3)
print(x) # Output: 5x3 array of random floats
Random Choice
# Randomly selecting elements from a list
x = random.choice([5, 3, 7, 8])
print(x) # Output: Random element from the list
x = random.choice([5, 3, 7, 8], size=10)
print(x) # Output: Array of 10 random elements from the list
x = random.choice([5, 3, 7, 8], size=(2, 3))
print(x) # Output: 2x3 array of random elements from the list
# Randomly selecting elements with probabilities
x = random.choice([5, 3, 7, 8], p=[0.1, 0.3, 0.6, 0.0], size=10)
print(x) # Output: Array of 10 elements selected based on probabilities
Shuffling and Permutations
# Shuffling an array in-place
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
o = x.copy()
random.shuffle(x)
print(o, x) # Output: Original array and shuffled array
# Generating a permuted array
y = random.permutation(x)
print(x, y) # Output: Original array and permuted array
Random Distributions
Normal Distribution
x = random.normal(size=5)
print(x) # Output: Array of 5 random numbers from a standard normal distribution
x = random.normal(loc=5, scale=3, size=5)
print(x) # Output: Array of 5 random numbers from N(5, 3^2)
# Visualizing the distribution
import matplotlib.pyplot as plt
import seaborn as sns
x = random.normal(loc=5, scale=3, size=1000)
sns.histplot(x)
plt.show()
Binomial Distribution
x = random.binomial(n=10, p=0.5, size=5)
print(x) # Output: Array of 5 random numbers from a binomial distribution
# Visualizing the distribution
x = random.binomial(n=5, p=0.7, size=10000)
sns.histplot(x, kde=False)
plt.show()
Poisson Distribution
x = random.poisson(lam=2, size=10)
print(x) # Output: Array of 10 random numbers from a Poisson distribution
# Visualizing the distribution
x = random.poisson(lam=2, size=1000)
sns.histplot(x, kde=False)
plt.show()
Uniform Distribution
x = random.uniform(size=10)
print(x) # Output: Array of 10 random numbers from a uniform distribution
# Visualizing the distribution
x = random.uniform(size=10000)
sns.histplot(x, kde=False)
plt.show()
Logistic Distribution
x = random.logistic(loc=1, scale=2, size=10)
print(x) # Output: Array of 10 random numbers from a logistic distribution
# Visualizing the distribution
x = random.logistic(loc=1, scale=2, size=10000)
sns.histplot(x, kde=False)
plt.show()
Multinomial Distribution
p = [1/6, 1/6, 1/6, 1/6, 1/6, 1/6]
x = random.multinomial(n=6, pvals=p, size=6)
print(x) # Output: 6x6 array of random numbers from a multinomial distribution
# Visualizing the distribution
x = random.multinomial(n=6, pvals=p, size=1000)
sns.histplot(x, kde=False)
plt.show()
Exponential Distribution
x = random.exponential(scale=2, size=6)
print(x) # Output: Array of 6 random numbers from an exponential distribution
# Visualizing the distribution
x = random.exponential(scale=2, size=1000)
sns.histplot(x, kde=False)
plt.show()
Chi-Square Distribution
x = random.chisquare(df=2, size=6)
print(x) # Output: Array of 6 random numbers from a chi-square distribution
# Visualizing the distribution
x = random.chisquare(df=2, size=1000)
sns.histplot(x, kde=False)
plt.show()
NumPy Arrays Math
Basic Array Arithmetic
import numpy as np
# Element-wise addition
a = [1, 2, 3, 4]
b = [15, 13, 12, 14]
c = np.add(a, b)
print(c) # Output: [16 15 15 18]
# Element-wise subtraction
z = np.subtract(a, b)
print(z) # Output: [-14 -11 -9 -10]
# Element-wise multiplication
z = np.multiply(a, b)
print(z) # Output: [15 26 36 56]
# Element-wise division
z = np.divide(a, b)
print(z) # Output: [0.06666667 0.15384615 0.25 0.28571429]
# Element-wise power
z = np.power(a, b)
print(z) # Output: [1 8192 531441 268435456]
# Element-wise modulus
z = np.mod(a, b)
print(z) # Output: [1 2 3 4]
# Element-wise remainder
z = np.remainder(a, b)
print(z) # Output: [1 2 3 4]
# Element-wise absolute value
x = np.array([-35, 11, 12, 13, 14, 15])
z = np.absolute(x)
print(z) # Output: [35 11 12 13 14 15]
Rounding Functions
x = np.array([-3.1666, 3.6667])
z = np.trunc(x)
print(z) # Output: [-3. 3.]
z = np.fix(x)
print(z) # Output: [-3. 3.]
z = np.around(x)
print(z) # Output: [-3. 4.]
z = np.floor(x)
print(z) # Output: [-4. 3.]
z = np.ceil(x)
print(z) # Output: [-3. 4.]
Logarithmic Functions
x = np.arange(1, 10)
z = np.log2(x)
print(z) # Output: [0. 1. 1.5849625 2. 2.32192809 2.5849625 2.80735492 3. 3.169925]
z = np.log10(x)
print(z) # Output: [0. 0.30103 0.47712125 0.60205999 0.69897 0.77815125 0.84509804
0.90308999 0.95424251]
z = np.log(x)
print(z) # Output: [0. 0.69314718 1.09861229 1.38629436 1.60943791 1.79175947
1.94591015 2.07944154 2.19722458]
Custom Ufuncs
def add3(x, y, z):
return x + y + z
add3func = np.frompyfunc(add3, 3, 1)
a = np.array([20, 21, 22, 23, 24, 25])
b = np.array([20, 21, 22, 23, 24, 25])
c = np.array([20, 21, 22, 23, 24, 25])
s = add3func(a, b, c)
print(s) # Output: [60 63 66 69 72 75]
Sum and Cumulative Sum
a = [1, 2, 3, 4]
s = [[1, 2, 3], [4, 2, 3]]
c = np.sum(a)
print(c) # Output: 10
c = np.sum(s, axis=1)
print(c) # Output: [6 9]
c = np.sum(s, axis=0)
print(c) # Output: [5 4 6]
c = np.cumsum(a)
print(c) # Output: [1 3 6 10]
c = np.cumsum(s, axis=0)
print(c) # Output: [[1 2 3] [5 4 6]]
c = np.cumsum(s, axis=1)
print(c) # Output: [[1 3 6] [4 6 9]]
Product and Cumulative Product
c = np.product(a)
print(c) # Output: 24
c = np.product(s, axis=0)
print(c) # Output: [4 4 9]
c = np.product(s, axis=1)
print(c) # Output: [6 24]
c = np.cumprod(a)
print(c) # Output: [1 2 6 24]
c = np.cumprod(s, axis=0)
print(c) # Output: [[1 2 3] [4 4 9]]
c = np.cumprod(s, axis=1)
print(c) # Output: [[1 2 6] [4 8 24]]
Differences
a = [12, 2, 5, 14]
c = np.diff(a)
print(c) # Output: [-10 3 9]
c = np.diff(a, n=2)
print(c) # Output: [13 6]
c = np.diff(s, axis=0)
print(c) # Output: [[3 0 0]]
c = np.diff(s, axis=1)
print(c) # Output: [[1 1] [-2 1]]
LCM and GCD
c = np.lcm(35, 49)
print(c) # Output: 245
c = np.lcm([35, 12], [49, 24])
print(c) # Output: [245 24]
c = np.lcm.reduce([3, 6, 9])
print(c) # Output: 18
c = np.gcd(35, 49)
print(c) # Output: 7
c = np.gcd([35, 15], [49, 12])
print(c) # Output: [7 3]
c = np.gcd.reduce([35, 15, 45])
print(c) # Output: 5
Trigonometric Functions
d = [0, 45, 90, 135, 180]
r = np.deg2rad(d)
print(r) # Output: [0. 0.78539816 1.57079633 2.35619449 3.14159265]
s = np.sin(r)
print(s) # Output: [0. 0.70710678 1. 0.70710678 0.]
s = np.cos(r)
print(s) # Output: [1. 0.70710678 0. -0.70710678 -1.]
s = np.tan(r)
print(s) # Output: [0. 1. 1.63312394e+16 -1. -1.22464680e-16]
s = np.sinh(r)
print(s) # Output: [0. 0.86867096 2.3012989 4.20311983 11.54873936]
s = np.arcsinh(s)
print(s) # Output: [0. 0.78539816 1.57079633 2.35619449 3.14159265]
Set Operations
c = np.unique([1, 1, 2, 3, 3, 2, 2, 1, 1, 4])
print(c) # Output: [1 2 3 4]
a = np.array([1, 2, 3, 4])
b = np.array([3, 4, 5, 6])
c = np.union1d(a, b)
print(c) # Output: [1 2 3 4 5 6]
c = np.intersect1d(a, b)
print(c) # Output: [3 4]
c = np.setdiff1d(a, b)
print(c) # Output: [1 2]
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )