NumPy Review

NumPy Review#

We might use numpy occasionally in this course. Here is a quick review of some common numpy functions and operations.

import numpy as np
# Creating an array and checking its shape
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr)
[[1 2 3]
 [4 5 6]
 [7 8 9]]
# Shape of the array:
print(arr.shape)
(3, 3)
# Zeros Array:
zeros = np.zeros((2, 3))
print(zeros)
[[0. 0. 0.]
 [0. 0. 0.]]
# Ones Array:
ones = np.ones((3, 2))
print(ones)
[[1. 1.]
 [1. 1.]
 [1. 1.]]
# Identity Matrix:
identity = np.eye(3)
print(identity)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
# Random Integer Array (0-9):
randint_arr = np.random.randint(0, 10, size=(2, 3))
print(randint_arr)
[[5 6 6]
 [6 6 2]]
# Random Float Array (0-1):
rand_arr = np.random.rand(2, 3)
print(rand_arr)
[[0.09298605 0.79698855 0.49523985]
 [0.70020571 0.73783847 0.27804818]]
# Indexing and Slicing
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Element at row 0, column 1:
print(arr[0, 1])
2
# First row:
print(arr[0, :])
[1 2 3]
# First column:
print(arr[:, 0])
[1 4 7]
# Element-wise Operations
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

print(arr1 + arr2)
print(arr1 - arr2)
print(arr1 * arr2)
print(arr1 / arr2)
[5 7 9]
[-3 -3 -3]
[ 4 10 18]
[0.25 0.4  0.5 ]
# operations between array and scalar
scalar = 5
print(arr + scalar)
[[ 6  7  8]
 [ 9 10 11]
 [12 13 14]]
# Common Functions
# Mean:
print(np.mean(arr))
print(np.sum(arr))
print(np.max(arr))
5.0
45
9
# You can also specify the axis along which to perform the operation.
# Mean along rows (axis=1):
print(np.mean(arr, axis=1))
[2. 5. 8.]
# Mean along columns (axis=0):
print(np.mean(arr, axis=0))
[4. 5. 6.]
# Reshaping Arrays
reshaped_arr = arr.reshape(1, 9)
print(reshaped_arr)
[[1 2 3 4 5 6 7 8 9]]
# Boolean Indexing
# Array > 5 gives:
print(arr > 5)
[[False False False]
 [False False  True]
 [ True  True  True]]
# collect all elements greater than 5
print(arr[arr > 5])
[6 7 8 9]
# Sum of True values (treating True as 1, False as 0):
print(np.sum(arr > 5))
4