Show Menu
Cheatography

Python (Numpy) Cheat Sheet (DRAFT) by

A cheatsheet on the Numpy package

This is a draft cheat sheet. It is a work in progress and is not finished yet.

numpy.n­darray

import numpy as np

# creating arrays
arr = np.array([1, 2, 3])                    # 1D array, shape (3,)
arr = np.array([[1, 2], [3, 4]])             # 2D array, shape (2, 2)
arr = np.zeros((rows, cols))                 # 2D array of zeros
arr = np.empty((rows, cols, channels))       # 3D array uninitialized

# inspecting arrays
arr.shape                                    # dimensions e.g. (480, 640, 3)
arr.dtype                                    # data type e.g. uint8, float32
arr.ndim                                     # number of dimensions
The core data structure in NumPy — a multi-­dim­ens­ional array of elements all of the same type.
More efficient than Python lists for numerical data as elements are stored contig­uously in memory.
Shape describes the dimensions — (rows, cols) for 2D, (rows, cols, channels) for 3D.
 

numpy.d­type

import numpy as np

# common dtypes
np.dtype(np.uint8)    # unsigned 8-bit integer  (0 to 255)
np.dtype(np.int8)     # signed 8-bit integer    (-128 to 127)
np.dtype(np.uint16)   # unsigned 16-bit integer (0 to 65535)
np.dtype(np.int16)    # signed 16-bit integer   (-32768 to 32767)
np.dtype(np.int32)    # signed 32-bit integer
np.dtype(np.float32)  # 32-bit floating point
np.dtype(np.float64)  # 64-bit floating point

# checking dtype
arr = np.array([1, 2, 3], dtype=np.float32)
arr.dtype             # float32
arr.itemsize          # bytes per element → 4
Describes the data type of elements stored in a numpy.n­da­rray.
Common types are uint8 for images (0-255), float32 for floating point, and int32 for integers.
The dtype determines how many bytes each element takes and how values are interp­reted.
 

numpy.u­int8

import numpy as np

arr = np.array([0, 128, 255], dtype=np.uint8)  # valid values
arr.dtype      # uint8
arr.itemsize   # 1 byte per element

# wrapping behaviour — values overflow silently
np.uint8(255) + np.uint8(1)   # returns 0, not 256

# common usage — converting to uint8 for image saving
arr = np.clip(arr, 0, 255).astype(np.uint8)   # safe conversion
An unsigned 8-bit integer type commonly used for image data.
Can hold values from 0 to 255 — exactly the range of a single colour channel in an image.
Values that exceed 255 wrap around rather than raising an error — a common source of bugs.