Tech

NumPy cheat sheet

NumPy cheat sheet. Explore our ultimate quick reference for NumPy.

NumPy is the foundational library for scientific computing in Python, providing robust support for large, multi-dimensional arrays and matrices. With its comprehensive mathematical functions, tools for integrating C/C++ and Fortran code, and capabilities for random number generation and Fourier transform, NumPy is indispensable for data analysis, machine learning, and scientific research. This cheat sheet offers a quick overview of NumPy's array creation, manipulation, and fundamental mathematical operations, tailored for beginners eager to dive into the world of numerical computing.

Getting Started

Introduction

To utilize the extensive features of NumPy, start by importing the library using the following convention:

import numpy as np

This import statement is standard in Python scripting and notebooks, allowing access to all of NumPy's functions, classes, and modules under the alias np.

Data Types

Type Description
np.int64 Signed 64-bit integer types
np.float32 Standard double-precision floating point
np.complex Complex numbers represented by 128 floats
np.bool Boolean type storing TRUE and FALSE values
np.object Python object type
np.string_ Fixed-length string type
np.unicode_ Fixed-length unicode type

Initial Placeholders

Function Description
np.zeros((3,4)) Create an array of zeros with shape (3,4)
np.ones((2,3,4),dtype=np.int16) Create an array of ones with shape (2,3,4) and type int16
np.arange(10,25,5) Create an array of evenly spaced values within a given interval
np.linspace(0,2,9) Create an array of evenly spaced values (number of samples)
np.full((3,5),7) Create a constant array with all values 7
np.eye(2) Create a 2X2 identity matrix
np.random.random((2,2)) Create an array with random values
np.empty((3,2)) Create an empty array

Commands and Functions

Saving & Loading On Disk

Function Description
np.save('my_array', a) Save an array to a binary file in NumPy .npy format
np.savez('array.npz', a, b) Save several arrays into a single file in uncompressed .npz format
np.load('my_array.npy') Load arrays from a .npy file

Saving & Loading Text Files

Function Description
np.loadtxt("myfile.txt") Load data from a text file
np.genfromtxt("my_file.csv", delimiter='') Load data from a text file, with missing values handled as specified
np.savetxt("myarray.txt", a, delimiter=" ") Save an array to a text file

Creating Arrays

- -
np.array([1,2,3]) 1D array
np.array([(1,2,3),(4,5,6)]) 2D array
np.zeros(3) 1D array of zeros
np.ones((3,4)) 2D array of ones
np.eye(5) 5x5 Identity matrix
np.linspace(0,100,6) Array of 6 evenly divided values from 0 to 100
np.arange(0,10,3) Array of values from 0 to less than 10 with step 3 (eg [0,3,6,9])
np.full((2,3),8) 2x3 array with all values 8
np.random.rand(4,5) 4x5 array of random floats between 0–1
np.random.rand(6,7)*100 6x7 array of random floats between 0–100
np.random.randint(5,size=(2,3)) 2x3 array with random ints between 0–4

Array Mathematics

Arithmetic Operations

Function Description
np.exp(b) Exponentiation
np.sqrt(b) Square root
np.sin(a) Sine of each element in the array
np.cos(b) Element-wise cosine
np.log(a) Element-wise natural logarithm
e.dot(f) Dot product

Comparison

Function Description
a == b Element-wise comparison
a < 2 Element-wise comparison
np.array_equal(a,b) Array-wise comparison

Aggregate Functions

Function Description
b.cumsum(axis=1) Cumulative sum of the elements

Array Manipulation

Transposing Array

Function Description
i = np.transpose(b) Permute array dimensions
i.T Permute array dimensions again

Changing Array Shape

Function Description
b.ravel() Flatten the array
g.reshape(3,-2) Reshape but don’t change data

Inspecting Properties

- -
arr.size Returns number of elements in arr
arr.shape Returns dimensions of arr (rows,columns)
arr.dtype Returns type of elements in arr
arr.astype(dtype) Convert arr elements to type dtype
arr.tolist() Convert arr to a Python list
np.info(np.eye) View documentation for np.eye

Copying/sorting/reshaping

- -
np.copy(arr) Copies arr to new memory
arr.view(dtype) Creates view of arr elements with type dtype
arr.sort() Sorts arr
arr.sort(axis=0) Sorts specific axis of arr
two_d_arr.flatten() Flattens 2D array two_d_arr to 1D
arr.T Transposes arr (rows become columns and vice versa)
arr.reshape(3,4) Reshapes arr to 3 rows, 4 columns without changing data
arr.resize((5,6)) Changes arr shape to 5x6 and fills new values with 0

Adding/removing Elements

- -
np.append(arr,values) Appends values to end of arr
np.insert(arr,2,values) Inserts values into arr before index 2
np.delete(arr,3,axis=0) Deletes row on index 3 of arr
np.delete(arr,4,axis=1) Deletes column on index 4 of arr

Combining/splitting

- -
np.concatenate((arr1,arr2),axis=0) Adds arr2 as rows to the end of arr1
np.concatenate((arr1,arr2),axis=1) Adds arr2 as columns to end of arr1
np.split(arr,3) Splits arr into 3 sub-arrays
np.hsplit(arr,5) Splits arr horizontally on the 5th index

Indexing/slicing/subsetting

- -
arr[5] Returns the element at index 5
arr[2,5] Returns the 2D array element on index [2][5]
arr[1]=4 Assigns array element on index 1 the value 4
arr[1,3]=10 Assigns array element on index [1][3] the value 10
arr[0:3] Returns the elements at indices 0,1,2 (On a 2D array: returns rows 0,1,2)
arr[0:3,4] Returns the elements on rows 0,1,2 at column 4
arr[:2] Returns the elements at indices 0,1 (On a 2D array: returns rows 0,1)
arr[:,1] Returns the elements at index 1 on all rows
arr<5 Returns an array with boolean values
(arr1<3) & (arr2>5) Returns an array with boolean values
~arr Inverts a boolean array
arr[arr<5] Returns array elements smaller than 5

Vector Math

- -
np.add(arr1,arr2) Elementwise add arr2 to arr1
np.subtract(arr1,arr2) Elementwise subtract arr2 from arr1
np.multiply(arr1,arr2) Elementwise multiply arr1 by arr2
np.divide(arr1,arr2) Elementwise divide arr1 by arr2
np.power(arr1,arr2) Elementwise raise arr1 raised to the power of arr2
np.array_equal(arr1,arr2) Returns True if the arrays have the same elements and shape
np.sqrt(arr) Square root of each element in the array
np.sin(arr) Sine of each element in the array
np.log(arr) Natural log of each element in the array
np.abs(arr) Absolute value of each element in the array
np.ceil(arr) Rounds up to the nearest int
np.floor(arr) Rounds down to the nearest int
np.round(arr) Rounds to the nearest int

Scalar Math

- -
np.add(arr,1) Add 1 to each array element
np.subtract(arr,2) Subtract 2 from each array element
np.multiply(arr,3) Multiply each array element by 3
np.divide(arr,4) Divide each array element by 4 (returns np.nan for division by zero)
np.power(arr,5) Raise each array element to the 5th power

Statistics

- -
np.mean(arr,axis=0) Returns mean along specific axis
arr.sum() Returns sum of arr
arr.min() Returns minimum value of arr
arr.max(axis=0) Returns maximum value of specific axis
np.var(arr) Returns the variance of array
np.std(arr,axis=1) Returns the standard deviation of specific axis
arr.corrcoef() Returns correlation coefficient of array