Numpy cheat sheet

From Notepedia
Jump to: navigation, search
Arrays and shape
import numpy as np

m = np.array([[1,1,1], [1,1,1]])
m.shape
>>> (2,3) 
# Output is (rows, columns)
Create an array using the arange np function
np.arange(start, stop, step)

n = np.arange(0, 40, 3) # start at 0 count up by 3's, stop before 40
>>> array([ 0,  3,  6,  9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39])
Reshape the array to be (rows, columns)
# reshape array to be 2x7
n = n.reshape(2, 7)
Return evenly spaces numbers over a specified interval using Linspace
o = np.linspace(0, 4, 9) # return 9 evenly spaced values from 0 to 4
>>> array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ])
Resize changes to shape and size of array in place
o.resize(3, 3)

>>> array([[ 0. ,  0.5,  1. ],
       [ 1.5,  2. ,  2.5],
       [ 3. ,  3.5,  4. ]])
Create arrays and fill them with specified values
# Array of ones 3 rows, 3 columns
np.ones((3,3)) 

# Array of Zeros
np.zeros((2,3))

# Diagonal ones 3 x 3
np.eye(3)

# Set diagonal numbers, and 0's elsewhere
np.diag(y)

Numpy Math Functions

Simple math functions in Numpy
a = np.array([-3, -2, 5, 2, 8])
a.sum()
a.max()
a.min()
a.mean()
a.std()

# These return the index of the min and max in the array
a.argmax()
a.argmin()

Indexing and slicing arrays

Crate some data to play with first
s = np.arange(10)**2
>>> array([ 0,  1,  4,  9, 16, 25, 36, 49, 64, 81])


# Return a tuple by referencing their indexes
s[0], s[4], s[-1]
>>> (0, 16, 81)
Slicing backwards and forwards using [start:stop:step]
# Pattern is [start:stop:step]
s[1:5]
>>> array([ 1,  4,  9, 16])

# Negatives count from the back
s[-4:]
>>> array([ 81, 100, 121, 144])

# This starts at the 5th last element, counts back by 2 all the way to the beginning
s[-5::-2]
Slicing multidimensional arrays
# Create an array with 36 slots starting from 0 to 35
r = np.arange(36)

# Turn the above array to a 6x6 arrary
r.resize((6,6))
>>> array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35]])

# Find the item at array slot row 2 column 2 starting at 0
r[2, 2]
>>> 14

# Find array on 3rd row cols 3 to 6
r[3, 3:6]
>>> array([21, 22, 23])

# Get the array in the first 2 rows in all columns but the last
r[:2, :-1]
>>> array([[ 0,  1,  2,  3,  4],
       [ 6,  7,  8,  9, 10]])
List comprehension
# Get values that are greater than 30
r[r > 30]
>>> array([31, 32, 33, 34, 35])

# For everything that's above 30, set it to 30
r[r > 30] = 30
>>> array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29],
       [30, 30, 30, 30, 30, 30]])
The above was quite basic, this page explains it better: http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/