Skip to main content
v2026.11,986 entries · CC-BY 4.0

NumPy Cheat Sheet: Arrays, Indexing, Broadcasting

NumPy cheat sheet for researchers: install, create and slice arrays, reshape, broadcast, save and fix import errors, checked against the NumPy 2.5 manual.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

This NumPy cheat sheet is a one-page map of the commands researchers use most: install with pip install numpy, import with import numpy as np, then create arrays, index and slice them, reshape, combine, summarise along an axis, broadcast and save results. Every snippet below is taken from the NumPy v2.5 user manual (absolute beginners guide, broadcasting guide and ImportError troubleshooting page), which we read on 2026-11-12, and each section names the page it comes from.

What NumPy is used for in research

NumPy provides the n-dimensional array (ndarray) that most Python analysis tools build on. In a research workflow it holds measurements, image matrices, simulation output and design matrices in one typed, rectangular block, and it applies arithmetic to the whole block at once instead of looping element by element. The attributes you check most often are a.ndim (number of dimensions), a.shape (length along each dimension), a.size (total element count) and a.dtype (element type). Elements are floating point (float64) by default when you create arrays with functions such as np.zeros.

This page is the overview. For single functions, see our guides to NumPy slicing, numpy.asarray, numpy.roll, numpy.indices and numpy.allclose.

How to install or access it

The NumPy install page (numpy.org/install, read 2026-11-12) lists these routes. It describes Python itself as the only prerequisite, and notes that the Anaconda Distribution includes both Python and NumPy.

  • pip: pip install numpy
  • conda: conda create -n my-env, then conda activate my-env, then conda install numpy (from the defaults or conda-forge channel).
  • Virtual environment with pip: python -m venv my-env, activate it with source my-env/bin/activate (macOS and Linux) or my-env\Scripts\activate (Windows), then pip install numpy.

To confirm the install worked, run import numpy as np and print(np.__version__). Keeping one environment per project makes it possible to reproduce the exact package versions behind a result later.

Step-by-step: the core commands

1. Create arrays

  1. Import the package: import numpy as np
  2. From a list: a = np.array([1, 2, 3, 4, 5, 6]). Nested lists give a two-dimensional array.
  3. Filled arrays: np.zeros(2), np.ones(2) and np.empty(2). The last one is uninitialised, so its contents are arbitrary until you assign values.
  4. Ranges: np.arange(4); np.arange(2, 9, 2) returns [2, 4, 6, 8]; np.linspace(0, 10, num=5) returns [0, 2.5, 5, 7.5, 10].
  5. Choose a type: np.ones(2, dtype=np.int64).
  6. Random numbers: rng = np.random.default_rng() then rng.integers(5, size=(2, 4)). The upper bound is exclusive, so values fall in [0, 5).

2. Index and slice

  • a[0] is the first element; a[:3] is the first three.
  • For a two-dimensional array m, m[1, 3] is row 1, column 3.
  • Boolean selection: m[m < 5] returns the elements below 5. np.nonzero(m < 5) returns a tuple of index arrays instead.

A slice is a view, not a copy. The table below shows the cases the manual documents.

Operation Result Effect of editing the result
b = a[3:] View of a b[0] = 40 also changes a
a.copy() Independent copy a is unchanged
x.ravel() Flattened view Can change x
x.flatten() Flattened copy x is unchanged

This is the most common source of silent errors when a cleaned subset is edited and the raw data changes with it. Call .copy() whenever the subset should be independent. More slicing patterns are in our NumPy slicing guide.

3. Reshape and change dimensions

  • a.reshape(3, 2) or np.reshape(a, shape=(1, 6), order='C'). The new shape must keep the same number of elements.
  • a[np.newaxis, :].shape is (1, 6); a[:, np.newaxis].shape is (6, 1). np.expand_dims(a, axis=1) does the same job with a named axis.
  • arr.T transposes.

4. Sort, combine, split, flip

  • np.sort(a)
  • np.concatenate((a, b), axis=0), np.vstack(...) and np.hstack(...)
  • np.hsplit(x, 3) splits into three equal parts; np.hsplit(x, (3, 4)) splits after columns 3 and 4.
  • np.flip(arr, axis=0) reverses along an axis.
  • np.unique(a, return_counts=True) returns the unique values and how often each occurs, which is a quick frequency table for coded survey responses.

5. Summarise along an axis

Methods such as arr.sum(axis=0), arr.min(axis=0) and arr.max(axis=1) collapse one axis. In a table where rows are observations and columns are variables, axis=0 works down the rows and gives one value per column. Plain arithmetic also applies to the whole array: data * 1.6 multiplies every element, an example of broadcasting a single number across an array.

6. Save and load

  • np.save('filename', a) writes filename.npy; np.load('filename.npy') reads it back.
  • np.savetxt('new_file.csv', arr) writes a text file; np.loadtxt('new_file.csv') reads it.

Use .npy for intermediate arrays you will reload in Python and a text format when another tool must read the file. To turn an existing list into an array before saving, see numpy.asarray.

Broadcasting: the rule behind most shape errors

The broadcasting guide (read 2026-11-12) states the rule in two parts. NumPy compares the shapes of two arrays starting from the trailing (rightmost) dimension and moving left. Two dimensions are compatible when they are equal or when one of them is 1. Missing leading dimensions are treated as size one, and each dimension of the result is the larger of the pair. If any pair is incompatible, NumPy raises a ValueError.

The data table below lists the shape pairs from the official guide, with the result shape for each.

Two worked cases from the guide show how the rule plays out in code:

  • a with shape (4, 3) plus b with shape (4,) fails with ValueError: operands could not be broadcast together with shapes (4,3) (4,), because the trailing dimensions are 3 and 4.
  • With a of shape (4,) and b of shape (3,), a[:, np.newaxis] + b gives shape (4, 3): adding an axis turns a into a column, and the sum is an outer sum.

Worked example: rescale each column of a data table

Suppose four observations of three variables are stored in an array d of shape (4, 3):

import numpy as np
d = np.array([[2., 10., 100.],
              [4., 20., 300.],
              [6., 30., 200.],
              [8., 40., 400.]])
lo = d.min(axis=0)      # shape (3,): [2., 10., 100.]
hi = d.max(axis=0)      # shape (3,): [8., 40., 400.]
scaled = (d - lo) / (hi - lo)

Here d - lo pairs shape (4, 3) with shape (3,). Reading from the right, 3 matches 3, and the missing leading dimension is treated as size one, so the result is (4, 3) and each column is shifted by its own minimum. The denominator hi - lo is shape (3,) and is broadcast the same way. The result has every column running from 0 to 1:

[[0.     0.     0.    ]
 [0.3333 0.3333 0.6667]
 [0.6667 0.6667 0.3333]
 [1.     1.     1.    ]]

(Values are shown to four decimals.) To select values meeting a condition, use boolean indexing: d[d < 5] returns [2., 4.]. To keep the results, save with np.save('scaled', scaled) and record the NumPy version from np.__version__ alongside the file so the analysis can be repeated.

Output and how to read it

  • Shape tuples: (4, 3) means 4 rows and 3 columns; (6,) is a one-dimensional array of six elements, which is not the same as (1, 6) or (6, 1).
  • dtype: an integer array and a float array print differently (2 versus 2.), and the default for np.zeros, np.ones and np.empty is float64.
  • Axis: the axis you name is the one that disappears from the output shape.
  • Tuples from nonzero: np.nonzero returns one index array per dimension, not a list of coordinates.

Troubleshooting

ImportError or ModuleNotFoundError on import numpy

The NumPy troubleshooting page (read 2026-11-12) lists these causes and fixes:

  • Broken install: run pip uninstall numpy, then pip install numpy.
  • Conda environment not active: run conda activate myenv (use your environment name).
  • Wrong interpreter in the IDE: point the editor at the interpreter of the environment where NumPy is installed.
  • Wrong path settings: inspect PYTHONPATH with print(os.environ.get('PYTHONPATH')) (after import os).

Errors after upgrading to NumPy 2

A package built against NumPy 1 can fail under NumPy 2 with messages such as _ARRAY_API not found, module compiled against API version v1 but this version of numpy is v2 or numpy.dtype size changed. The page gives two fixes: pip install 'numpy<2' is the quickest, and upgrading the affected package with pip install package_name --upgrade is the preferred one. It also advises reading the traceback from the bottom up and looking at the first frame outside NumPy to find the package responsible.

ValueError: operands could not be broadcast together

Print the .shape of both operands and compare them from the right using the rule above. Adding an axis with np.newaxis or np.expand_dims usually resolves a row-versus-column mix-up.

Task Command Further reading
Slice and index a[:3], m[1, 3] NumPy slicing
Convert a sequence to an array np.array numpy.asarray
Shift elements along an axis Covered in the linked guide numpy.roll
Index grids Covered in the linked guide numpy.indices
Compare floats within tolerance Covered in the linked guide numpy.allclose

Free alternatives

NumPy is itself free and open source. The packages below are free tools that sit alongside it or build on it; each description is taken from that project’s own documentation (read 2026-11-12), and none replaces the n-dimensional array that this cheat sheet covers.

Package How its documentation describes it Relationship to NumPy
SciPy Open-source software for mathematics, science and engineering Complements NumPy for scientific computing
pandas Data structures for working with relational or labeled data Built on top of NumPy
JAX A Python library for accelerator-oriented array computation and program transformation Offers a NumPy-style API through jax.numpy

FAQ

How do I install NumPy?

Run pip install numpy, ideally inside a virtual environment, or conda install numpy inside a conda environment. Then confirm with import numpy as np; print(np.__version__).

What is the difference between ravel and flatten?

ravel() returns a view where possible, so edits can reach the original, while flatten() always returns a copy.

Does slicing copy the data?

No. A slice such as a[3:] is a view, and changing it changes a. Use a.copy() for an independent array.

Which broadcasting shapes are compatible?

Compare dimensions from the right; each pair must be equal or contain a 1. For example (4, 3) with (3,) works, and (4, 3) with (4,) does not.

Should I save with np.save or np.savetxt?

np.save writes a binary .npy file that np.load reads back; np.savetxt writes a text file that np.loadtxt reads back and that other programs can open.

Sources

Data: NumPy broadcasting: shape pairs and result shapes

Shape pairs taken from the NumPy v2.5 broadcasting guide, with the resulting shape or whether NumPy raises a ValueError, compiled by applying the guide's right-to-left rule to each listed pair.

NumPy broadcasting: shape pairs and result shapes
Shape of array AShape of array BResult shapeCompatible
5x415x4yes
5x445x4yes
15x3x515x1x515x3x5yes
15x3x53x515x3x5yes
15x3x53x115x3x5yes
8x1x6x17x1x58x7x6x5yes
34none (ValueError)no
2x18x4x3none (ValueError)no

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about NumPy Cheat Sheet: Arrays, Indexing, Broadcasting

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →