Sitemap
Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Essential NumPy Cheatsheet

Quickly learn and reference essential NumPy functions and techniques.

7 min readNov 1, 2024

--

Press enter or click to view image in full size

NumPy is one of Python’s core libraries for numerical computing, providing fast and efficient operations on large arrays and matrices. It’s a must-have tool for data science, machine learning, and scientific computing.

Hi, my name is CyCoderX and this article is a cheat sheet covering the most commonly used NumPy functions and features — from array creation to statistical analysis, slicing, and transformations. Whether you’re new to NumPy or looking for a refresher, this guide will provide a quick reference to some of the most essential commands.

Let’s dive in!

I write articles for everyone to enjoy, and I’d love your support by following me for more Python, SQL, Data Engineering and Data Science content.😊

Creating Arrays

Creating arrays is the foundation of using NumPy effectively. Arrays in NumPy can be created from lists, generated from scratch, or initialized with specific properties.

  • From Lists
    Convert a Python list into a NumPy array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
  • Using arange
    Create arrays with a range of values. Similar to Python’s range() function but returns a NumPy array:
arr = np.arange(0, 10, 2)  # Output: [0, 2, 4, 6, 8]
  • Using linspace
    Generate evenly spaced values between a start and end point:
arr = np.linspace(0, 1, 5)  # Output: [0. , 0.25, 0.5 , 0.75, 1. ]
  • Zeros and Ones
    Create arrays filled with zeros or ones:
arr_zeros = np.zeros((3, 3))
arr_ones = np.ones((2, 4))
  • Random Arrays
    Generate arrays with random values using:
  • Uniform distribution: np.random.rand()
  • Standard normal distribution: np.random.randn()
  • Random integers: np.random.randint(low, high, size)
random_array = np.random.randint(0, 10, (3, 3))

Basic Array Operations

Once you have an array, you can perform various operations on it. These include mathematical calculations, array-wide functions, and element-wise operations.

  • Basic Math Operations
    You can add, subtract, multiply, and divide arrays directly. NumPy will apply these operations element-wise.
arr = np.array([1, 2, 3])
arr_add = arr + 2 # Output: [3, 4, 5]
arr_mul = arr * 3 # Output: [3, 6, 9]
  • Aggregation Functions
    NumPy provides functions for array-wide calculations like sum, mean, max, and min.
arr = np.array([1, 2, 3, 4, 5])
arr_sum = arr.sum() # Output: 15
arr_mean = arr.mean() # Output: 3.0
arr_max = arr.max() # Output: 5
  • Statistical Functions
    Functions like std, var, median, and percentile allow for statistical analysis on arrays.
arr_std = arr.std()     # Standard deviation
arr_var = arr.var() # Variance
arr_median = np.median(arr)
  • Element-wise Functions
    Operations like np.sqrt, np.exp, and np.log apply to each element individually:
arr_sqrt = np.sqrt(arr)  # Square root of each element

Array Indexing, Slicing, and Reshaping

Efficient indexing and slicing are core to NumPy, allowing quick access and manipulation of specific elements, rows, columns, or sub-arrays within larger arrays.

  • Indexing and Slicing
    Arrays can be sliced like Python lists but support multidimensional slicing.
arr = np.array([1, 2, 3, 4, 5])
sliced_arr = arr[1:4] # Output: [2, 3, 4]
  • 2D Indexing
    In 2D arrays, specify rows and columns separately:
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
element = arr_2d[1, 2] # Output: 6 (2nd row, 3rd column)
  • Boolean Indexing
    Boolean conditions can be applied to filter values in arrays.
filtered_arr = arr[arr > 2]  # Elements greater than 2
  • Reshaping Arrays
    You can change the shape of an array without modifying its data using reshape.
arr = np.arange(1, 10)
reshaped_arr = arr.reshape(3, 3)
  • Flattening Arrays
    Convert a multi-dimensional array into a single-dimensional array:
flattened = arr.ravel()

Broadcasting and Vectorization

Broadcasting is a powerful feature in NumPy that allows operations on arrays of different shapes, reducing the need for explicit loops.

  • Broadcasting Basics
    Broadcasting lets you perform operations on arrays of different sizes. For example, you can add a scalar to an array, and NumPy will automatically apply the scalar to each element:
arr = np.array([1, 2, 3])
result = arr + 5 # Output: [6, 7, 8]
  • Vectorized Operations
    NumPy performs operations at the element level by default, enabling faster, more efficient calculations than typical Python loops.
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
result = a * b # Output: [4, 10, 18]
Press enter or click to view image in full size

Linear Algebra Functions

NumPy includes a suite of linear algebra functions, which are essential for scientific computing, data science, and machine learning applications.

  • Matrix Multiplication
    Use dot for matrix multiplication between two arrays.
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
result = np.dot(a, b)
# Output: [[19, 22], [43, 50]]
  • Transpose
    Transpose an array, swapping rows and columns:
a = np.array([[1, 2], [3, 4]])
a_transposed = a.T
# Output: [[1, 3], [2, 4]]
  • Determinant
    Calculate the determinant of a matrix using linalg.det:
det = np.linalg.det(a)
  • Inverse
    Compute the inverse of a square matrix with linalg.inv:
inverse = np.linalg.inv(a)
  • Eigenvalues and Eigenvectors
    Use linalg.eig to calculate eigenvalues and eigenvectors:
eigenvalues, eigenvectors = np.linalg.eig(a)

Random Sampling with random

NumPy’s random module is packed with functions to create arrays with random values, useful for simulations, initializing weights in machine learning models, and data augmentation.

  • Random Floats
    Generate random floats between 0 and 1 with rand:
random_floats = np.random.rand(3, 3)
  • Random Integers
    Create random integers in a specified range using randint:
random_ints = np.random.randint(0, 10, (2, 3))
  • Normal Distribution
    Generate numbers from a normal (Gaussian) distribution with randn:
normal_dist = np.random.randn(3, 3)
  • Setting a Random Seed
    Setting a seed ensures reproducible results in random sampling:
np.random.seed(42)
  • Choice
    Select random elements from a given array:
arr = np.array([10, 20, 30, 40])
random_choice = np.random.choice(arr, 2) # Randomly selects two elements

Saving and Loading Arrays

NumPy provides convenient methods to save arrays to files and load them back, ensuring data persistence across sessions or sharing.

  • Saving Arrays
    Use save to store an array in a binary .npy file:
np.save('array_file', arr)
  • Loading Arrays
    Load an array from a .npy file with load:
loaded_arr = np.load('array_file.npy')
  • Saving Multiple Arrays
    Save multiple arrays in a compressed .npz format:
np.savez('arrays_file.npz', arr1=arr1, arr2=arr2)
  • Loading Multiple Arrays
    Load multiple arrays from an .npz file:
data = np.load('arrays_file.npz')
arr1_loaded = data['arr1']
arr2_loaded = data['arr2']

Advanced Array Manipulations

NumPy provides several advanced methods for manipulating arrays, making it possible to efficiently handle complex data transformations.

  • Concatenating Arrays
    Combine arrays along different axes using concatenate:
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])
combined = np.concatenate((arr1, arr2), axis=0)
# Output: [[1, 2], [3, 4], [5, 6], [7, 8]]
  • Stacking Arrays
    Stack arrays vertically or horizontally with vstack and hstack:
vertical_stack = np.vstack((arr1, arr2))  # Vertically stacks arrays
horizontal_stack = np.hstack((arr1, arr2)) # Horizontally stacks arrays
  • Splitting Arrays
    Split an array into multiple sub-arrays with split, hsplit, or vsplit:
arr = np.array([1, 2, 3, 4, 5, 6])
split_arr = np.split(arr, 3) # Output: [array([1, 2]), array([3, 4]), array([5, 6])]
  • Tile and Repeat
    Duplicate elements or sub-arrays across specified dimensions:
  1. Repeat replicates elements within an array:
repeated = np.repeat(arr, 2)

2. Tile replicates an entire array in block form:

tiled = np.tile(arr, (2, 1))  # Output: array repeated across rows
  • Flattening Arrays
    Convert a multi-dimensional array to a one-dimensional array using flatten or ravel:
flat_array = arr.flatten()

Conclusion

NumPy is an incredibly powerful library for data manipulation, scientific computing, and machine learning. In this cheat sheet, we covered some of the most commonly used functions in NumPy, from array creation and basic operations to random sampling, saving/loading arrays, and advanced manipulations. With a strong grasp of these functions, you’ll be able to handle most data tasks quickly and efficiently, allowing you to focus more on analysis and insights.

Get CyCoderX’s stories in your inbox

Join Medium for free to get updates from this writer.

Whether you’re a beginner or a seasoned data professional, knowing how to leverage these essential NumPy functions will streamline your work and improve your coding efficiency. Save this cheat sheet as a quick reference to help you make the most out of NumPy in your projects.

Happy Coding!

Always conduct your own research and verify online information. Relying on others can lead to outdated practices, so take the initiative to implement and refine code to suit your needs. Note that I am not sponsored or affiliated with any services or products mentioned; my advice comes from my own experiences.

Press enter or click to view image in full size

Final Words:

Thank you for taking the time to read my article.
This article was first published on Medium by CyCoderX.

Hi, I’m CyCoderX! I’m a data engineer passionate about sharing knowledge, I write articles about Python, SQL, Data Science, Data Engineering, lifestyle and more!

What did you think about this article? Let me know in the comments below … or above, depending on your device!

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

--

--

CyCoderX
CyCoderX

Written by CyCoderX

Machine Learning & Data Engineer | Data Science | Python & SQL | AI | Software Developer | Azure & AWS Cloud Specialist | Blogger simplifying Big Data & Trends

Python in Plain English
Python in Plain English

Published in Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.