NumPy is the foundational library for numerical computing in Python, providing efficient multi-dimensional array objects (ndarray) and a vast collection of mathematical functions that operate on arrays. Built on optimized C and Fortran libraries (BLAS/LAPACK), NumPy enables vectorized operations that eliminate Python loops and execute at near-native speed. Understanding broadcasting rules, memory layout, and array views versus copies is essential β these concepts allow you to write code that is not only fast but also memory-efficient, forming the backbone of scientific Python workflows from data analysis to deep learning.
What This Cheat Sheet Covers
This topic spans 23 focused tables and 219 indexed concepts, 129 flashcards. Below is a complete table-by-table outline of this topic, spanning foundational concepts through advanced details.
A jump-to index of every table row in this cheat sheet.
An interactive map of every table and concept in this topic.
Table 1: Array Creation β Initialization and Construction
Every NumPy workflow starts by getting data into an array, and there are many doors in. Use np.array() when you already have the values, zeros, ones, or empty to pre-allocate a buffer you'll fill later, and arange or linspace to generate evenly spaced sequences. The specialized constructorsβeye, diag, fromfunctionβsave you from building common matrix patterns by hand.
| Method | Example | Description | |
|---|---|---|---|
arr = np.array([1, 2, 3]) | β’ Create array from Python list or tuple β’ most common creation method for known data | ||
np.zeros((3, 4)) | β’ Initialize array filled with zeros β’ specify shape as tuple | ||
np.ones((2, 3), dtype=int) | β’ Create array filled with ones β’ optional dtype specification | ||
np.empty((2, 2)) | β’ Allocate uninitialized array β’ fastest creation but contains arbitrary values | ||
np.full((3, 3), 7) | Fill array with specified constant value. | ||
np.arange(0, 10, 2) | β’ Generate evenly spaced values within interval β’ works like Python range() but returns ndarray | ||
np.linspace(0, 1, 50) | Create array of specified number of evenly spaced points including endpoints. | ||
np.logspace(0, 3, 4) | β’ Generate logarithmically spaced values β’ useful for exponential scales. | ||
np.eye(3) | Create identity matrix with ones on diagonal and zeros elsewhere. | ||
np.identity(4) | β’ Square identity matrix β’ equivalent to np.eye(n) for square matrices | ||
np.diag([1, 2, 3]) | Extract diagonal or construct diagonal matrix from 1D array. | ||
np.fromfunction(lambda i,j: i+j, (3,3)) | β’ Construct array by executing function over each coordinate β’ indices passed as arguments |