Numpy - Cheatsheet

By xngo on April 5, 2019

# Import
    import numpy as np
 
# Slicing narray
    sma_x = sma_x[4:]   # Skip 1st 4 due to period=5.
 
# Slicing.
    a = np.array([1,2]) # [x,y]
    b = np.array([3,5]) # [x,y]
 
    p1 = np.array([2,4]) # [x,y]
    p2 = np.array([2,3]) # [x,y]
 
    data_points = np.array([a,b]) # Add points: (1,2) , (3,5)
    data_points_x = data_points[:,0] # For every point, get 1st value, which is x.
    data_points_y = data_points[:,1] # For every point, get 2nd value, which is y.
    print(data_points_y) # [2, 5]
 
# Copy values from list of indexes
    arr = np.array([100.10, 200.42, 4.14, 89.00, 34.55, 1.12])
    arr[ [1,4,5] ] # Get indexes: 1,4,5.
    #[ 200.42,   34.55,    1.12]
 
# Create a range.
    xs = np.arange(start = 1, stop = 10, step = 1, dtype='int')
    print(xs.dtype) # int64
 
# Reshape
    np.arange(start = 1, stop = 10, step = 1).reshape((3,3))
    [
        [1 2 3]
        [4 5 6]
        [7 8 9]
    ]
 
# Generate random numbers.
    # Positive integer only. There is no randfloat().
    np.random.randint(low=1,high=100,size=(4,4),dtype='int')
 
    # Random float.
    np.random.random(12)
 
    # Random distribution include negative number.
    np.random.normal(loc = 0, scale = 1, size = 10) # Return an array of 10 rnd.
    np.random.normal(loc = 0, scale = 1, size = (3,3)) # Return 3 by 3 array.
 
    np.absolute() to convert to positive.
 
# Generate evenly spaced numbers over a specified interval.
    np.linspace(0, 100, num=5, dtype='int')   # [  0  25  50  75 100]
    np.linspace(0, 100, num=5, dtype='float') # [   0.   25.   50.   75.  100.]
 
# Not a number(nan)
    narray = np.array([1.0,2.0,3.0])
    narray[1] = np.nan # Set 2.0 as Not a Number(nan)
    for value in narray:
        if np.isnan(value): # Can also use math.isnan() v2.6+
            print(value, "is not a number.")
        else:
            print(value, "is a number.")    
 

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.