Blog Logo

27-Aug-2024 ~ 4 min read

NumPy Cheatsheet: Your Go-To Guide for Array Manipulation


NumPy Cheatsheet: Your Go-To Guide for Array Manipulation

Creating Arrays:

  • np.array(list): Create an array from a Python list.
import numpy as np
my_list = [1, 2, 3, 4, 5]
my_array = np.array(my_list)
print(my_array)  # Output: [1 2 3 4 5]
  • np.zeros((rows, cols)): Create an array filled with zeros.
zeros_array = np.zeros((2, 3))
print(zeros_array)
# Output:
# [[0. 0. 0.]
#  [0. 0. 0.]]
  • np.ones((rows, cols)): Create an array filled with ones.
ones_array = np.ones((3, 2))
print(ones_array)
# Output:
# [[1. 1.]
#  [1. 1.]
#  [1. 1.]]
  • np.arange(start, stop, step): Create an array with evenly spaced values.
range_array = np.arange(0, 10, 2)
print(range_array)  # Output: [0 2 4 6 8]
  • np.linspace(start, stop, num): Create an array with evenly spaced values within a given range.
linspace_array = np.linspace(0, 1, 5)
print(linspace_array)
# Output: [0.   0.25 0.5  0.75 1.  ]
  • np.random.rand(rows, cols): Create an array with random values between 0 and 1.
random_array = np.random.rand(2, 2)
print(random_array)
# Output: An array with random values between 0 and 1.

Array Attributes:

  • array.shape: Returns the dimensions of the array.
print(my_array.shape)  # Output: (5,)
  • array.ndim: Returns the number of dimensions.
print(zeros_array.ndim)  # Output: 2
  • array.size: Returns the total number of elements.
print(my_array.size)  # Output: 5
  • array.dtype: Returns the data type of the elements.
    print(my_array.dtype)  # Output: int64

Array Indexing and Slicing:

  • array[index]: Access an element by its index.
    print(my_array[2])  # Output: 3
  • array[start:stop:step]: Slice a portion of the array.
print(my_array[1:4])  # Output: [2 3 4]
  • array[rows, cols]: Access elements by row and column indices.
print(zeros_array[0, 1])  # Output: 0.0
  • array[boolean_mask]: Access elements based on a boolean mask.
mask = my_array > 2
print(my_array[mask])  # Output: [3 4 5]

Array Operations:

  • array + scalar: Add a scalar to each element.
print(my_array + 5)  # Output: [ 6  7  8  9 10]
  • array1 + array2: Element-wise addition of two arrays.
array2 = np.array([10, 20, 30, 40, 50])
print(my_array + array2)
# Output: [11 22 33 44 55]
  • array * scalar: Multiply each element by a scalar.
print(my_array * 2)  # Output: [ 2  4  6  8 10]
  • array1 * array2: Element-wise multiplication of two arrays.
print(my_array * array2)
# Output: [10 40 90 160 250]
  • np.dot(array1, array2): Matrix multiplication.
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
print(np.dot(matrix1, matrix2))
# Output:
# [[19 22]
#  [43 50]]
  • np.sum(array): Sum of all elements.
print(np.sum(my_array))  # Output: 15
  • np.mean(array): Mean of all elements.
print(np.mean(my_array))  # Output: 3.0
  • np.median(array): Median of all elements.
print(np.median(my_array))  # Output: 3.0
  • np.std(array): Standard deviation of all elements.
print(np.std(my_array))  # Output: 1.4142135623730951
  • np.max(array): Maximum value.
  print(np.max(my_array))  # Output: 5
  • np.min(array): Minimum value.
print(np.min(my_array))  # Output: 1

Reshaping and Transposing:

  • array.reshape((new_rows, new_cols)): Reshape the array.
reshaped_array = my_array.reshape((1, 5))
print(reshaped_array)
# Output: [[1 2 3 4 5]]
  • array.transpose(): Transpose the array.
transposed_array = reshaped_array.transpose()
print(transposed_array)
# Output:
# [[1]
#  [2]
#  [3]
#  [4]
#  [5]]

Broadcasting:

NumPy allows operations between arrays of different shapes under certain conditions. This is called broadcasting.

Linear Algebra:

  • np.linalg.inv(matrix): Inverse of a matrix.
matrix = np.array([[1, 2], [3, 4]])
print(np.linalg.inv(matrix))
# Output:
# [[-2.   1. ]
#  [ 1.5 -0.5]]
  • np.linalg.det(matrix): Determinant of a matrix.
print(np.linalg.det(matrix))  # Output: -2.0
  • np.linalg.solve(A, b): Solve a linear system of equations.
A = np.array([[2, 3], [1, -2]])
b = np.array([8, 1])
print(np.linalg.solve(A, b))
# Output: [3. 1.]

Other Useful Functions:

  • np.where(condition, x, y): Return elements from x or y depending on a condition.
print(np.where(my_array > 3, my_array, 0))
# Output: [0 0 0 4 5]
  • np.concatenate((array1, array2)): Concatenate arrays.
concatenated_array = np.concatenate((my_array, array2))
print(concatenated_array)
# Output: [ 1  2  3  4  5 10 20 30 40 50]
  • np.split(array, indices): Split an array into sub-arrays.
split_arrays = np.split(my_array, [2, 4])
print(split_arrays)
# Output: [array([1, 2]), array([3, 4]), array([5])]

For a comprehensive understanding, refer to the official NumPy documentation: https://numpy.org/doc/