NumPy Cheat Sheet Flashcards
A NumPy Array object shorthand
arr
Import NumPy
import numpy as np
Import from a text file
np.loadtxt(‘file.txt’)
Import from a CSV file
np.genfromtxt(‘file.csv’,delimiter=‘,’)
Writes to a text file
np.savetxt(‘file.txt’,arr,delimiter=‘ ‘)
Writes to a CSV file
np.savetext(‘file.csv’,arr,delimiter=‘,’)
Create one dimensional array
np.array([1,2,3])
Create two dimensional array
np.array([(1,2,3),(4,5,6)])
Create 1D array of length 3 all values 0
np.zeros(3)
3 x 4 array with all values 1
np.ones((3,4)
5 x 5 array of 0 with 1 on diagonal (identity matrix)
np.eye(5)
Array of 6 evenly divided values from 0 to 100
np.linspace(0,100,6)
Array of values from 0 to less than 10 with step 3
np.arange(0,10,3)
2 x 3 array with all values 8
np.full((2,3),8)
4 x 5 array of random floats between 0-1
np.random.rand(4,5)
6 x 7 array of random floats between 0-100
np.random.rand(6,7)*100
2 x 3 array with random ints between 0-4
np.random.randint(5,size=2,3))
Returns number of elements in arr
arr.size
Returns dimensions of arr
arr.shape
Returns the type of elements in arr
arr.dtype
Convert arr elements to type dtype
arr.astype(dtype)
Convert arr to a Python list
arr.tolist()
View documentation for np.eye
np.info(np.eye)
Copies arr to new memory
np.copy(arr)
Creates view of arr elements with type dtype
arr.view(dtype)
Sorts arr
arr.sort()
Sorts specific axis of arr
arr.sort(axis=0)
Flattens 2D array two_d_arr to 1D
two_d_arr.flatten()
Transposes arr (rows become columns and vice versa)
arr.T
Reshapes arr to 3 rows, 4 columns without changing data
arr.reshape(3,4)