# NumPy Cheatsheet

> Every example from DataCamp's NumPy cheat sheet, run in NumPy 2.4, each with a picture of what happens to the array. Lines that no longer work in NumPy 2 are corrected.

- Published: 2026-11-15
- URL: https://latentstate.dev/posts/numpy-cheatsheet/
- Topics: Machine Learning

---

All examples from DataCamp's [NumPy cheat sheet](https://assets.datacamp.com/blog_assets/Numpy_Python_Cheat_Sheet.pdf), run in NumPy 2.4. Each one has its code and a picture. The pictures are drawn by running that same code, so they show what NumPy actually returns.

How to read the pictures: a filled cell is one the operation selects, reads or produces. A thick outline marks cells a step has just written. Dashed, faded cells are values NumPy repeats by broadcasting. Small numbers in a cell's corner give element order. Grey numbers along the edges are indices, counted from zero.

Where the original sheet fails or is wrong in NumPy 2, the example is fixed and the text says what changed. The examples use these arrays:

```python
import numpy as np

a = np.array([1, 2, 3])
b = np.array([(1.5, 2, 3), (4, 5, 6)], dtype=float)
c = np.array([[(1.5, 2, 3), (4, 5, 6)], [(3, 2, 1), (4, 5, 6)]], dtype=float)
d = np.arange(10, 25, 5)
e = np.full((2, 2), 7)
f = np.eye(2)
g = a - b
```

## Creating arrays

### 1D, 2D, 3D

Axes are numbered from the outside in, and axis 0 is the first index. In a 2D array axis 0 runs over the rows. In a 3D array it runs over the blocks.

```python
a = np.array([1, 2, 3])
b = np.array([(1.5, 2, 3), (4, 5, 6)], dtype=float)
c = np.array([[(1.5, 2, 3), (4, 5, 6)], [(3, 2, 1), (4, 5, 6)]], dtype=float)
```

![Axes are numbered from the outside in, and axis 0 is the first index](https://latentstate.dev/_astro/fig-arrays-light.BOZNUXfr.png)

## Initial placeholders

### np.zeros

A new array of the given shape filled with 0. The default type is float64, hence `0.`.

```python
np.zeros((3, 4))
```

![A new array of the given shape filled with 0](https://latentstate.dev/_astro/fig-zeros-light.DjBvXOAE.png)

### np.ones

Ones, here as 16-bit integers. Shape (2, 3, 4) means 2 blocks of 3 rows and 4 columns.

```python
np.ones((2, 3, 4), dtype=np.int16)
```

![Ones, here as 16-bit integers](https://latentstate.dev/_astro/fig-ones-light.BT8Tgj8O.png)

### np.arange

Values from start up to stop with a fixed step. Stop itself is excluded, so 25 is not in the result.

```python
d = np.arange(10, 25, 5)
```

![Values from start up to stop with a fixed step](https://latentstate.dev/_astro/fig-arange-light.F6J7Cu-4.png)

### np.linspace

A fixed number of evenly spaced values, both ends included. 9 samples from 0 to 2 give a step of 0.25.

```python
np.linspace(0, 2, 9)
```

![A fixed number of evenly spaced values, both ends included](https://latentstate.dev/_astro/fig-linspace-light.B_RBYKTg.png)

### np.full

Any shape, filled with one constant.

```python
e = np.full((2, 2), 7)
```

![Any shape, filled with one constant](https://latentstate.dev/_astro/fig-full-light.sgYa-FMN.png)

### np.eye

An identity matrix: ones on the diagonal, zeros elsewhere.

```python
f = np.eye(2)
```

![An identity matrix: ones on the diagonal, zeros elsewhere](https://latentstate.dev/_astro/fig-eye-light.BDhKr61V.png)

### np.random.random

Uniform random floats from 0 (included) to 1 (excluded). New code usually writes `np.random.default_rng().random((2, 2))`.

```python
np.random.random((2, 2))
```

![Uniform random floats from 0 (included) to 1 (excluded)](https://latentstate.dev/_astro/fig-random-light.Dp5vQaNY.png)

### np.empty

Allocates memory without initialising it. The values are whatever was in that memory before, so fill the array before you read it.

```python
np.empty((3, 2))
```

![Allocates memory without initialising it](https://latentstate.dev/_astro/fig-empty-light.BB5LvVF9.png)

## I/O

### np.save, np.load

`np.save` writes one array in NumPy's binary .npy format and adds the extension itself. The file holds a small header with the type and shape, then the raw bytes: 3 int64 values take 24 bytes.

```python
np.save('my_array', a)
np.load('my_array.npy')
```

![np.save writes one array in NumPy's binary .npy format and adds the extension itself](https://latentstate.dev/_astro/fig-save-load-light.BZZTtXo3.png)

### np.savez

Several arrays in one uncompressed .npz archive. Arrays passed by position are named arr_0, arr_1 and so on; pass keywords, as in `np.savez('array.npz', a=a, b=b)`, to choose the names. `np.savez_compressed` compresses.

```python
np.savez('array.npz', a, b)
np.load('array.npz')['arr_1']
```

![Several arrays in one uncompressed .npz archive](https://latentstate.dev/_astro/fig-savez-light.CMLwSGRW.png)

### np.savetxt, np.loadtxt

Plain text, one row per line. The default format is `%.18e`, so every number is written as a float and `loadtxt` reads floats back. Pass `fmt='%d'` to write integers.

```python
np.savetxt('myarray.txt', a, delimiter=' ')
np.loadtxt('myarray.txt')
```

![Plain text, one row per line](https://latentstate.dev/_astro/fig-savetxt-loadtxt-light.CKNf7kBR.png)

### np.genfromtxt

Like `loadtxt`, but it copes with missing values: the empty field becomes `nan`.

```python
np.genfromtxt('my_file.csv', delimiter=',')
```

![Like loadtxt, but it copes with missing values: the empty field becomes nan](https://latentstate.dev/_astro/fig-genfromtxt-light.DI3lL46B.png)

## Data types

### dtypes

A type fixes how many bytes one element takes. Several names on the original sheet were removed in NumPy 2. `np.complex`, `np.object`, `np.string_` and `np.unicode_` are now `np.complex128`, `np.object_`, `np.bytes_` and `np.str_`. The sheet also calls float32 double precision, but it is single precision; double is float64. An object array stores 8-byte pointers, and a unicode string uses 4 bytes per character.

```python
np.int64       # signed 64-bit integer
np.float32     # single-precision float
np.complex128  # complex number, two float64
np.bool        # True / False
np.object_     # any Python object
np.bytes_      # fixed-length byte string, e.g. 'S5'
np.str_        # fixed-length unicode string, e.g. 'U5'
```

![A type fixes how many bytes one element takes](https://latentstate.dev/_astro/fig-dtypes-light.DN_NTJz6.png)

## Inspecting your array

### a.shape

The size along each axis, as a tuple. A 1D array gives a one-element tuple.

```python
a.shape
```

![The size along each axis, as a tuple](https://latentstate.dev/_astro/fig-shape-light.CHRZAx73.png)

### len

`len` counts only the first axis, so for a 2D array it gives the number of rows, not the number of elements.

```python
len(b)    # len(a) is 3
```

![len counts only the first axis, so for a 2D array it gives the number of rows, not the number of elements](https://latentstate.dev/_astro/fig-len-light.ChOg6bq5.png)

### b.ndim

The number of axes.

```python
b.ndim
```

![The number of axes](https://latentstate.dev/_astro/fig-ndim-light.Blsl3XTC.png)

### e.size

The total number of elements, the product of the shape.

```python
e.size
```

![The total number of elements, the product of the shape](https://latentstate.dev/_astro/fig-size-light.Bx6CbHrS.png)

### b.dtype

The element type, as a dtype object and as its name.

```python
b.dtype
b.dtype.name
```

![The element type, as a dtype object and as its name](https://latentstate.dev/_astro/fig-dtype-light.COH4EhJz.png)

### b.astype

Converts to another type and returns a copy. Float to int truncates toward zero, so 1.5 becomes 1.

```python
b.astype(int)
```

![Converts to another type and returns a copy](https://latentstate.dev/_astro/fig-astype-light.rHxGw5dI.png)

## Asking for help

### np.info

Prints the documentation of any NumPy object. `help()` works too.

```python
np.info(np.ndarray.dtype)
```

![Prints the documentation of any NumPy object](https://latentstate.dev/_astro/fig-info-light.DtdQwdfS.png)

## Arithmetic

### a - b

Element by element. a has shape (3,) and b has shape (2, 3), so NumPy broadcasts a over every row of b (the dashed row). The function form is the same operation.

```python
g = a - b
np.subtract(a, b)
```

![Element by element](https://latentstate.dev/_astro/fig-subtract-light.BtuoPbOM.png)

### b + a

Addition, broadcast the same way. The order of the operands does not matter for broadcasting.

```python
b + a
np.add(b, a)
```

![Addition, broadcast the same way](https://latentstate.dev/_astro/fig-add-light.C_nyVKmj.png)

### a / b

`/` always returns floats, even for two integer arrays. `//` is integer division.

```python
a / b
np.divide(a, b)
```

![/ always returns floats, even for two integer arrays](https://latentstate.dev/_astro/fig-divide-light.Cew5vTqg.png)

### a * b

`*` multiplies element by element. It is not the matrix product; that is `dot` or `@`, below.

```python
a * b
np.multiply(a, b)
```

![* multiplies element by element](https://latentstate.dev/_astro/fig-multiply-light.C2px3VEj.png)

### np.exp

Element-wise math functions keep the shape. This one is e to the power of each element.

```python
np.exp(b)
```

![Element-wise math functions keep the shape](https://latentstate.dev/_astro/fig-exp-light.CHKHTXXc.png)

### np.sqrt

Square root of each element.

```python
np.sqrt(b)
```

![Square root of each element](https://latentstate.dev/_astro/fig-sqrt-light.DwJHRfNY.png)

### np.sin

Sine of each element, in radians.

```python
np.sin(a)
```

![Sine of each element, in radians](https://latentstate.dev/_astro/fig-sin-light.BKPCxagT.png)

### np.cos

Cosine of each element, in radians.

```python
np.cos(b)
```

![Cosine of each element, in radians](https://latentstate.dev/_astro/fig-cos-light.DgPZFwYb.png)

### np.log

Natural logarithm of each element: log(1) is 0. `np.log10` and `np.log2` are the other bases.

```python
np.log(a)
```

![Natural logarithm of each element: log(1) is 0](https://latentstate.dev/_astro/fig-log-light.CDtLlI4O.png)

### e.dot(f)

The matrix product: each result cell is a row of e times a column of f, summed. f is the identity, so the result equals e.

```python
e.dot(f)
e @ f
```

![The matrix product: each result cell is a row of e times a column of f, summed](https://latentstate.dev/_astro/fig-dot-light.DiVzQ192.png)

## Comparison

### a == b

Element-wise comparison gives a bool array and broadcasts like arithmetic.

```python
a == b
```

![Element-wise comparison gives a bool array and broadcasts like arithmetic](https://latentstate.dev/_astro/fig-equal-light.bPr6rDXS.png)

### a < 2

Comparing with a number compares every element with it.

```python
a < 2
```

![Comparing with a number compares every element with it](https://latentstate.dev/_astro/fig-less-light.Wj_WxhKY.png)

### np.array_equal

One bool for the whole array: True only if the shapes and all the values match. Here the shapes differ.

```python
np.array_equal(a, b)
```

![One bool for the whole array: True only if the shapes and all the values match](https://latentstate.dev/_astro/fig-array-equal-light.CfOQ4Ldh.png)

## Aggregate functions

### a.sum

Adds up all elements.

```python
a.sum()
```

![Adds up all elements](https://latentstate.dev/_astro/fig-sum-light.Cjb-HNLK.png)

### a.min

The smallest element. `a.argmin()` gives its index.

```python
a.min()
```

![The smallest element](https://latentstate.dev/_astro/fig-min-light.Iwl2wCLh.png)

### b.max(axis=0)

With `axis=0` the reduction runs along axis 0, down the rows, so each column gives one value. The sheet says 'of an array row', but for `axis=0` it is the maximum of each column.

```python
b.max(axis=0)
```

![With axis=0 the reduction runs along axis 0, down the rows, so each column gives one value](https://latentstate.dev/_astro/fig-max-axis0-light.BzAIC9Ys.png)

### b.cumsum(axis=1)

A running sum along each row. The shape stays the same.

```python
b.cumsum(axis=1)
```

![A running sum along each row](https://latentstate.dev/_astro/fig-cumsum-axis1-light.v-JsqyES.png)

### a.mean

The arithmetic mean of all elements.

```python
a.mean()
```

![The arithmetic mean of all elements](https://latentstate.dev/_astro/fig-mean-light.DZWvzVue.png)

### np.median

There is no `b.median()` method, so the sheet's line raises AttributeError. Use `np.median`. With six values the median is the mean of the middle two, 3 and 4.

```python
np.median(b)
```

![There is no b.median() method, so the sheet's line raises AttributeError](https://latentstate.dev/_astro/fig-median-light.BUkGI1VF.png)

### np.corrcoef

There is no `a.corrcoef()` method either. `np.corrcoef` treats each row as a variable and returns their correlation matrix. The two rows of b are almost perfectly correlated.

```python
np.corrcoef(b)
```

![There is no a.corrcoef() method either](https://latentstate.dev/_astro/fig-corrcoef-light.BbeoY1p-.png)

### np.std

The standard deviation of all elements. By default it is the population version (`ddof=0`); pass `ddof=1` for the sample version.

```python
np.std(b)
```

![The standard deviation of all elements](https://latentstate.dev/_astro/fig-std-light.B2GzsjAN.png)

## Copying arrays

### a.view

A view shares memory with the original, so writing through h changes a too.

```python
h = a.view()
h[0] = 9
```

![A view shares memory with the original, so writing through h changes a too](https://latentstate.dev/_astro/fig-view-light.Ch4MOlFP.png)

### a.copy

`a.copy()` and `np.copy(a)` both make an independent copy, so a stays unchanged.

```python
h = a.copy()    # or np.copy(a)
h[0] = 9
```

![a.copy() and np.copy(a) both make an independent copy, so a stays unchanged](https://latentstate.dev/_astro/fig-copy-light.ieZbCo0c.png)

## Sorting arrays

### x.sort

Sorts in place and returns None; `np.sort(x)` returns a sorted copy instead. The sheet's a is already sorted, so this example uses x.

```python
x = np.array([3, 1, 2])
x.sort()
```

![Sorts in place and returns None; np.sort(x) returns a sorted copy instead](https://latentstate.dev/_astro/fig-sort-light.-j2kwGFU.png)

### c.sort(axis=0)

Sorts along axis 0: each position is sorted across the two blocks. Only the 3 and the 1 in the corner are out of order, so only they swap.

```python
c.sort(axis=0)
```

![Sorts along axis 0: each position is sorted across the two blocks](https://latentstate.dev/_astro/fig-sort-axis0-light.CGuTC-ax.png)

## Subsetting, slicing, indexing

### a[2]

The element at index 2.

```python
a[2]
```

![The element at index 2](https://latentstate.dev/_astro/fig-index-1d-light.BGAcGvBf.png)

### b[1, 2]

Row 1, column 2. The same as `b[1][2]`, but one indexing step instead of two.

```python
b[1, 2]
```

![Row 1, column 2](https://latentstate.dev/_astro/fig-index-2d-light.Cs56IgKq.png)

### a[0:2]

Start is included, stop is excluded: indices 0 and 1.

```python
a[0:2]
```

![Start is included, stop is excluded: indices 0 and 1](https://latentstate.dev/_astro/fig-slice-1d-light.DOl9e9-5.png)

### b[0:2, 1]

Rows 0 and 1 of column 1. A single index drops its axis, so the result is 1D.

```python
b[0:2, 1]
```

![Rows 0 and 1 of column 1](https://latentstate.dev/_astro/fig-slice-column-light.CtU8ATBr.png)

### b[:1]

A slice keeps its axis: `b[:1]` is 2D with one row, while `b[0]` would be 1D. The same as `b[0:1, :]`.

```python
b[:1]
```

![A slice keeps its axis: b[:1] is 2D with one row, while b[0] would be 1D](https://latentstate.dev/_astro/fig-slice-row-light.DYIrF5Cc.png)

### c[1, ...]

`...` stands for as many `:` as needed, so `c[1, ...]` is `c[1, :, :]`, the second block. The sheet prints it with one bracket too many; the result is 2D.

```python
c[1, ...]
```

![](https://latentstate.dev/_astro/fig-ellipsis-light.Du-Vd-H6.png)

### a[::-1]

A negative step walks backwards. The small numbers show where each element came from. The result is a view, not a copy.

```python
a[::-1]
```

![A negative step walks backwards](https://latentstate.dev/_astro/fig-reverse-light.VzTJAIrN.png)

### a[a < 2]

A bool array used as an index keeps the elements where it is True. The result is always 1D and always a copy.

```python
a[a < 2]
```

![A bool array used as an index keeps the elements where it is True](https://latentstate.dev/_astro/fig-boolean-index-light.3E40GldB.png)

### b[[1, 0, 1, 0], [0, 1, 2, 0]]

Two index lists pair up into (1, 0), (0, 1), (1, 2) and (0, 0). The small numbers show the order. Fancy indexing returns a copy.

```python
b[[1, 0, 1, 0], [0, 1, 2, 0]]
```

![Two index lists pair up into (1, 0), (0, 1), (1, 2) and (0, 0)](https://latentstate.dev/_astro/fig-fancy-index-light.C0FBa4eD.png)

### b[[1, 0, 1, 0]][:, [0, 1, 2, 0]]

First rows 1, 0, 1, 0, then columns 0, 1, 2, 0 of that result: a 4x4 grid with repeated rows and columns. `b[np.ix_([1, 0, 1, 0], [0, 1, 2, 0])]` does it in one step.

```python
b[[1, 0, 1, 0]][:, [0, 1, 2, 0]]
```

![First rows 1, 0, 1, 0, then columns 0, 1, 2, 0 of that result: a 4x4 grid with repeated rows and columns](https://latentstate.dev/_astro/fig-fancy-grid-light.Ddh5fQ3Z.png)

### a[1:3] = 1

Not on the sheet: assigning through slices. `a[1:3]` is short for `a[1:3, :]`, and the single number on the right is broadcast to every selected cell. Rows that are not next to each other take a list: `a[[0, 3]] = 1`.

```python
a = np.zeros((4, 4))
a[1:3] = 1     # rows 1 and 2
a[:, 3] = 1    # column 3
```

![Not on the sheet: assigning through slices](https://latentstate.dev/_astro/fig-fill-rows-column-light.CoPpWLIz.png)

## Changing shape

### np.transpose

Swaps the axes, so row 0 becomes column 0. `.T` is the short form, and transposing twice gives b back.

```python
i = np.transpose(b)
i.T
```

![Swaps the axes, so row 0 becomes column 0](https://latentstate.dev/_astro/fig-transpose-light.DICjJtO-.png)

### b.ravel

Flattens to 1D in row order.

```python
b.ravel()
```

![Flattens to 1D in row order](https://latentstate.dev/_astro/fig-ravel-light.DWXaHihx.png)

### g.reshape

The same data in a new shape; the elements keep their order. `-1` means 'work this size out'. The sheet writes `-2`, which NumPy happens to accept, but `-1` is the documented value.

```python
g.reshape(3, -1)
```

![The same data in a new shape; the elements keep their order](https://latentstate.dev/_astro/fig-reshape-light.0xNUqlTP.png)

### resize

The sheet calls `h.resize` on a view, which raises `ValueError: cannot resize this array: it does not own its data`. On an array that owns its data, the method works in place and pads with zeros. The function `np.resize` returns a new array and repeats the data instead.

```python
h = b.copy()
h.resize((2, 6))
np.resize(b, (2, 6))
```

![The sheet calls h.resize on a view, which raises ValueError: cannot resize this array: it does not own its data](https://latentstate.dev/_astro/fig-resize-light.CD7iYe2_.png)

## Adding and removing elements

### np.append

Flattens both arrays and joins them into a new 1D array. Pass `axis=` to keep the shape.

```python
np.append(a, b)
```

![Flattens both arrays and joins them into a new 1D array](https://latentstate.dev/_astro/fig-append-light.BP5YksoL.png)

### np.insert

Inserts 5 before index 1 and returns a new array. A NumPy array never grows in place.

```python
np.insert(a, 1, 5)
```

![Inserts 5 before index 1 and returns a new array](https://latentstate.dev/_astro/fig-insert-light.D3SzLpF6.png)

### np.delete

Removes index 1 and returns a new array.

```python
np.delete(a, [1])
```

![Removes index 1 and returns a new array](https://latentstate.dev/_astro/fig-delete-light.DJNVp8qu.png)

## Combining arrays

### np.concatenate

Joins arrays along an axis they already have.

```python
np.concatenate((a, d), axis=0)
```

![Joins arrays along an axis they already have](https://latentstate.dev/_astro/fig-concatenate-light.Cb6K8VMG.png)

### np.vstack

Stacks rows: a becomes the first row and b's rows follow.

```python
np.vstack((a, b))
```

![Stacks rows: a becomes the first row and b's rows follow](https://latentstate.dev/_astro/fig-vstack-light.yz5EkPx5.png)

### np.r_

Index-style shorthand that concatenates along axis 0, here the same as `np.vstack((e, f))`.

```python
np.r_[e, f]
```

![Index-style shorthand that concatenates along axis 0, here the same as np.vstack((e, f))](https://latentstate.dev/_astro/fig-r--light.B_WToGc4.png)

### np.hstack

Joins side by side, along axis 1.

```python
np.hstack((e, f))
```

![Joins side by side, along axis 1](https://latentstate.dev/_astro/fig-hstack-light.CPa_iYbb.png)

### np.column_stack

Turns 1D arrays into columns. `np.c_[a, d]` gives the same result.

```python
np.column_stack((a, d))
np.c_[a, d]
```

![Turns 1D arrays into columns](https://latentstate.dev/_astro/fig-column-stack-light.D7ofaN5U.png)

## Splitting arrays

### np.hsplit

Splits into 3 equal pieces along axis 1, which for a 1D array is its only axis. The result is a list of arrays.

```python
np.hsplit(a, 3)
```

![Splits into 3 equal pieces along axis 1, which for a 1D array is its only axis](https://latentstate.dev/_astro/fig-hsplit-light.Uag_u_ud.png)

### np.vsplit

Splits along axis 0 into 2 pieces, here the two blocks of c. The values the sheet prints for this line are wrong; the picture shows the real ones.

```python
np.vsplit(c, 2)
```

![Splits along axis 0 into 2 pieces, here the two blocks of c](https://latentstate.dev/_astro/fig-vsplit-light.CBaIZeaL.png)
