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. Below is a complete table-by-table outline of this topic, spanning foundational concepts through advanced details.
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 |