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, thenconda activate my-env, thenconda install numpy(from the defaults or conda-forge channel). - Virtual environment with pip:
python -m venv my-env, activate it withsource my-env/bin/activate(macOS and Linux) ormy-env\Scripts\activate(Windows), thenpip 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
- Import the package:
import numpy as np - From a list:
a = np.array([1, 2, 3, 4, 5, 6]). Nested lists give a two-dimensional array. - Filled arrays:
np.zeros(2),np.ones(2)andnp.empty(2). The last one is uninitialised, so its contents are arbitrary until you assign values. - 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]. - Choose a type:
np.ones(2, dtype=np.int64). - Random numbers:
rng = np.random.default_rng()thenrng.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)ornp.reshape(a, shape=(1, 6), order='C'). The new shape must keep the same number of elements.a[np.newaxis, :].shapeis(1, 6);a[:, np.newaxis].shapeis(6, 1).np.expand_dims(a, axis=1)does the same job with a named axis.arr.Ttransposes.
4. Sort, combine, split, flip
np.sort(a)np.concatenate((a, b), axis=0),np.vstack(...)andnp.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)writesfilename.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:
awith shape (4, 3) plusbwith shape (4,) fails withValueError: operands could not be broadcast together with shapes (4,3) (4,), because the trailing dimensions are 3 and 4.- With
aof shape (4,) andbof shape (3,),a[:, np.newaxis] + bgives shape (4, 3): adding an axis turnsainto 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 (
2versus2.), and the default fornp.zeros,np.onesandnp.emptyisfloat64. - Axis: the axis you name is the one that disappears from the output shape.
- Tuples from nonzero:
np.nonzeroreturns 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, thenpip 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
PYTHONPATHwithprint(os.environ.get('PYTHONPATH'))(afterimport 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.
Related functions and where to read more
| 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
- NumPy v2.5 manual, NumPy: the absolute basics for beginners, numpy.org/doc/stable/user/absolute_beginners.html, read 2026-11-12.
- NumPy, Installing NumPy, numpy.org/install, read 2026-11-12.
- NumPy v2.5 manual, Broadcasting, numpy.org/doc/stable/user/basics.broadcasting.html, read 2026-11-12.
- NumPy v2.5 manual, Troubleshooting ImportError, numpy.org/doc/stable/user/troubleshooting-importerror.html, read 2026-11-12.
- SciPy documentation, docs.scipy.org/doc/scipy, read 2026-11-12.
- pandas documentation, Package overview, pandas.pydata.org, read 2026-11-12.
- JAX documentation, docs.jax.dev, read 2026-11-12.
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.
| Shape of array A | Shape of array B | Result shape | Compatible |
|---|---|---|---|
| 5x4 | 1 | 5x4 | yes |
| 5x4 | 4 | 5x4 | yes |
| 15x3x5 | 15x1x5 | 15x3x5 | yes |
| 15x3x5 | 3x5 | 15x3x5 | yes |
| 15x3x5 | 3x1 | 15x3x5 | yes |
| 8x1x6x1 | 7x1x5 | 8x7x6x5 | yes |
| 3 | 4 | none (ValueError) | no |
| 2x1 | 8x4x3 | none (ValueError) | no |
Sources
- NumPy v2.5 manual: Broadcasting (accessed 2026-11-12)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







