The Ultimate NumPy Cheat Sheet

NumPy, short for Numerical Python, is a powerful library in Python for numerical computations. It provides a multidimensional array object, along with a vast collection of functions to manipulate arrays efficiently. Whether you’re a beginner or an experienced Python developer, having a handy cheat sheet for NumPy can be immensely helpful.

Each item in the cheat sheet will be explained in detail, accompanied by code examples, their corresponding outputs, and comprehensive explanations to demonstrate its usage. By the end of this article, you’ll have a comprehensive reference to refer to whenever you need to work with NumPy arrays.

Let’s dive right into our NumPy cheat sheet:

  1. Creating NumPy Arrays
import numpy as np

# Creating a 1D array
arr1 = np.array([1, 2, 3, 4, 5])
print(arr1)

# Creating a 2D array filled with zeros
arr2 = np.zeros((3, 4))
print(arr2)

Explanation:

  • The code imports the NumPy library using the alias np.
  • np.array([1, 2, 3, 4, 5]) creates a 1D array arr1 with values [1, 2, 3, 4, 5].
  • np.zeros((3, 4)) creates a 2D array arr2 with dimensions 3×4, filled with zeros.

Output:

arr1: [1 2 3 4 5]
arr2:
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
  1. Array Arithmetic
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Addition
result_add = arr1 + arr2
print(result_add)

# Multiplication
result_mul = arr1 * arr2
print(result_mul)

Explanation:

  • The code imports NumPy and creates two 1D arrays, arr1 and arr2.
  • arr1 + arr2 performs element-wise addition of the arrays.
  • arr1 * arr2 performs element-wise multiplication of the arrays.

Output:

result_add: [5 7 9]
result_mul: [4 10 18]
  1. Array Aggregation
import numpy as np

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

# Sum of array elements
sum_arr = np.sum(arr)
print(sum_arr)

# Maximum element
max_arr = np.max(arr)
print(max_arr)

Explanation:

  • The code creates a 1D array arr with values [1, 2, 3, 4, 5].
  • np.sum(arr) computes the sum of all elements in the array.
  • np.max(arr) returns the maximum element in the array.

Output:

sum_arr: 15
max_arr: 5
  1. Reshaping Arrays
import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])

# Reshaping the array to a 2D matrix
reshaped_arr = arr.reshape((2, 3))
print(reshaped_arr)

# Resizing the array to a different shape
resized_arr = np.resize(arr, (3, 4))
print(resized_arr)

Explanation:

  • The code creates a 1D array arr with values [1, 2, 3, 4, 5, 6].
  • arr.reshape((2, 3)) reshapes the array to a 2D matrix with dimensions 2×3.
  • np.resize(arr, (3, 4)) resizes the array to a different shape, resulting in a 3×4 matrix.

Output:

reshaped_arr:
[[

1 2 3]
 [4 5 6]]

resized_arr:
[[1 2 3 4]
 [5 6 1 2]
 [3 4 5 6]]
  1. Broadcasting
import numpy as np

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

# Broadcasting scalar to array
result = a + b
print(result)

Explanation:

  • The code creates a 1D array a with values [1, 2, 3] and a scalar b with value 2.
  • a + b demonstrates broadcasting, where the scalar b is automatically extended to match the shape of array a.
  • The addition operation is performed element-wise.

Output:

result: [3 4 5]

  1. Array Indexing and Slicing
import numpy as np

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

# Accessing an element
print(arr[2])

# Slicing a subset
print(arr[1:4])

# Reversing the array
print(arr[::-1])

Explanation:

  • The code creates a 1D array arr with values [1, 2, 3, 4, 5].
  • arr[2] accesses the element at index 2, which is the third element in the array.
  • arr[1:4] slices a subset of the array, including elements at indices 1, 2, and 3.
  • arr[::-1] reverses the order of the elements in the array.

Output:

3
[2 3 4]
[5 4 3 2 1]
  1. Array Concatenation
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Concatenating arrays horizontally
result_h = np.hstack((arr1, arr2))
print(result_h)

# Concatenating arrays vertically
result_v = np.vstack((arr1, arr2))
print(result_v)

Explanation:

  • The code creates two 1D arrays, arr1 and arr2, with values [1, 2, 3] and [4, 5, 6], respectively.
  • np.hstack((arr1, arr2)) concatenates the arrays horizontally, resulting in a new 1D array.
  • np.vstack((arr1, arr2)) concatenates the arrays vertically, creating a new 2D array.

Output:

result_h: [1 2 3 4 5 6]
result_v:
[[1 2 3]
 [4 5 6]]
  1. Random Number Generation
import numpy as np

# Generating random integers
rand_ints = np.random.randint(low=1, high=10, size=5)
print(rand_ints)

# Generating random floats
rand_floats = np.random.uniform(low=0.0, high=1.0, size=3)
print(rand_floats)

Explanation:

  • The code uses NumPy’s random module to generate random numbers.
  • np.random.randint(low=1, high=10, size=5) generates an array of 5 random integers between 1 (inclusive) and 10 (exclusive).
  • np.random.uniform(low=0.0, high=1.0, size=3) generates an array of 3 random floats between 0.0 (inclusive) and 1.0 (exclusive).

Output:

rand_ints: [4 7 6 5 8]
rand_floats: [0.60179106 0.52392394 0.11379281]
  1. Boolean Indexing
import numpy as np

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

# Boolean indexing with condition
result = arr[arr > 2]
print(result)

Explanation:

  • The code creates a 1D array arr with values [1, 2, 3, 4, 5].
  • `arr2` creates a boolean mask where each element is compared with the condition (> 2).
  • arr[arr > 2] applies the boolean mask to the array, returning only the elements that satisfy the condition.

Output:

result: [3 4 5]
  1. Array Transposition
import numpy as np

arr = np.array([[1, 2, 3],
                [4, 5, 6]])

# Transposing the array
transposed_arr = arr.T
print(transposed_arr)

Explanation:

  • The code creates a 2D array arr with dimensions 2×3.
  • arr.T transposes the array, swapping its rows and columns.

Output:

transposed_arr:
[[1 4]
 [2 5]
 [3 6]]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top