NumPy Cheatsheet
Introduction NumPy (Numerical Python) is a core library for scientific computing in
Python. It provides a high-performance multidimensional array object and tools for working
with these arrays.
Importing NumPy
Python
import numpy as np
Creating Arrays
• np.array([1, 2, 3]): Create an array from a list or tuple.
• np.zeros((3, 4)): Create an array of zeros with a specified
shape.
• np.ones((2, 2)): Create an array of ones.
• np.arange(10): Create an array with a sequence of numbers from
0 to 9.
• np.linspace(0, 1, 5): Create an array of 5 evenly spaced
numbers between 0 and 1.
• np.random.rand(2, 3): Create an array with random numbers
from a uniform distribution.
• np.random.randint(0, 10, size=5): Create an array of
random integers between 0 and 9.
Array Attributes
• arr.dtype: The data type of the array's elements.
• arr.ndim: The number of dimensions (axes).
• arr.shape: A tuple of the array's dimensions.
• arr.size: The total number of elements in the array.
Indexing and Slicing
• arr[2]: Access the element at index 2.
• arr[1:4]: Get a slice from index 1 up to (but not including) 4.
• arr[2:]: Get a slice from index 2 to the end of the array.
• arr[::-1]: Reverse the array.
• arr_2d[0, 1]: Access the element at row 0, column 1 in a 2D
array.
• arr_2d[:, 1]: Get all elements from the second column.
Array Manipulation
• arr.reshape(2, 3): Gives a new shape to an array without
changing its data.
• arr.T: Transpose the array (swap rows and columns).
• np.concatenate((a, b)): Joins a sequence of arrays.
• np.vstack((a, b)): Stacks arrays vertically (as new rows).
• np.hstack((a, b)): Stacks arrays horizontally (as new
columns).
• arr.flatten(): Returns a copy of the array collapsed into one
dimension.
Mathematical Operations
• Element-wise operations: Standard operators (+, -, *, /) apply to
each element.
◦ a + b
◦ a * 2
• Matrix multiplication: Use the @ operator or np.dot().
◦ a @ b
◦ np.dot(a, b)
• Statistical functions:
◦ np.sum(arr): Sum of all elements.
◦ np.mean(arr, axis=0): Mean of each column.
◦ np.max(arr): Maximum value in the array.
◦ np.std(arr): Standard deviation.
Broadcasting NumPy can perform operations on arrays of different shapes. The smaller
array is "broadcast" across the larger one. For example, np.array([1, 2, 3]) + 5
becomes [6, 7, 8].
Logical and Boolean Indexing
• arr > 5: Returns a boolean array indicating which elements are
greater than 5.
• arr[arr > 5]: Returns a new array containing only the elements
that satisfy the condition.
• np.where(arr > 5, 1, 0): Replaces elements based on a
condition; if > 5, replace with 1, otherwise 0.