Python, NumPy, and Vectorization Cheat Sheet

1. Importing NumPy

import numpy as np

2. Vector Creation

# Create a vector of zeros
a = np.zeros(4)
Output: [0. 0. 0. 0.]

# Create a vector with random values
a = np.random.random_sample(4)
Output: [0.74228696 0.1674833 0.42629983 0.92137134]

# Create a vector with a range of values
a = np.arange(4.)
Output: [0. 1. 2. 3.]

# Create a vector manually
a = np.array([5, 4, 3, 2])
Output: [5 4 3 2]

# Check vector shape
a.shape
Output: (4,)

# Check data type
a.dtype
Output: dtype('int64')

3. Vector Indexing and Slicing

a = np.arange(10)
a = [0 1 2 3 4 5 6 7 8 9]

# Indexing
print(a[2])
Output: 2
print(a[-1])
Output: 9 (last element)

# Slicing
print(a[2:7:1])
Output: [2 3 4 5 6]
print(a[2:7:2])
Output: [2 4 6]
print(a[3:])
Output: [3 4 5 6 7 8 9]
print(a[:3])
Output: [0 1 2]

4. Vector Operations

a = np.array([1, 2, 3, 4])
a = [1 2 3 4]

# Negation
print(-a)
Output: [-1 -2 -3 -4]

# Sum of elements
print(np.sum(a))
Output: 10

# Mean of elements
print(np.mean(a))
Output: 2.5

# Element-wise squaring
print(a**2)
Output: [1 4 9 16]

# Scalar multiplication
print(5 * a)
Output: [5 10 15 20]

# Element-wise operations
b = np.array([-1, -2, 3, 4])
print(a + b)
Output: [0 0 6 8]

# Dot product
print(np.dot(a, b))
Output: 24

# Custom dot product (for-loop based)
def my_dot(a, b):
    result = 0
    for i in range(len(a)):
        result += a[i] * b[i]
    return result
print(my_dot(a, b))
Output: 24

5. Matrix Creation

# Create a 2D array
a = np.zeros((2, 3))
Output:
[[0. 0. 0.]
[0. 0. 0.]]


# Create a matrix manually
a = np.array([[1, 2, 3],
[4, 5, 6]])
Output:
[[1 2 3]
[4 5 6]]


# Reshape an array
a = np.arange(6).reshape(-1, 2)
Output:
[[0 1]
[2 3]
[4 5]]

6. Matrix Indexing and Slicing

a = np.arange(20).reshape(-1, 10)
a =
[[ 0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]]


# Access an element
print(a[1, 2])
Output: 12

# Access a row
print(a[1])
Output: [10 11 12 13 14 15 16 17 18 19]

# Slice columns
print(a[:, 2:7:1])
Output:
[[ 2 3 4 5 6]
[12 13 14 15 16]]


# Access all elements
print(a[:, :])
Output:
[[ 0 1 2 3 4 5 6 7 8 9]
[10 11 12 13 14 15 16 17 18 19]]

7. Vectorization vs. Loops

8. Broadcasting

9. Common Pitfalls

10. Useful NumPy Functions

Remember to always check the shape of your arrays using array.shape to ensure your operations are valid!