Import library

import numpy as np

Checking

Isinstance

# Check if an object is an instance numpy array?
type(MyObect).__module__ == np.__name__

Comparing

Compare 2 dicts of multiple objects:

# 2 dicts of multiple objects
def _compare_two_dict(dct_1, dct_2):
    return np.array([(lambda key: (dct_1[key] == dct_2[key]).all()
       if type(dct_1[key]).__module__ == np.__name__
       else dct_1[key] == dct2[key])(key)
       for key in dct_1]).all()
# 2 numpy arrays containing `np.nan`
def nan_equal(a,b):
    try:
        np.testing.assert_equal(a,b)
    except AssertionError:
        return False
    return True

# if using in a pytest
# instead of `assert np.testing`,
# just use
np.testing.assert_equal(a,b)

Count 0, NaNs

# count nans
arr = [1,2,3,4, np.nan,np.nan, 0,0,0]
np.isnan(arr).sum() # 2
# count non-nans
arr = [1,2,3,4, np.nan,np.nan, 0,0,0]
np.count_nonzero(~np.isnan(arr)) # 7
# count non-zeros
arr = [1,2,3,4, np.nan,np.nan, 0,0,0]
np.count_nonzero(arr) # 6

Creating

Random numbers

# random int between 0, 5
np.random.randint(5)

# random int between [1, 100]
np.random.randint(1, 100 + 1)
# random array of int between 1, 5
np.random.randint(1,5,size=(2,3))

# random array of int between 0, 3
np.random.randint(3,size=(2,3))
# random float number between [0, 1)
np.random.random()
# random float number between [a, b)
(b - a)*np.random.random() + a
# array of random between [0, 1)
np.random.random_sample((5,)) # size: 5x1
# array of random between (a, b)
(b - a)*np.random.random_sample((5,1)) + a

Equal size

Create evenly spaced numbers over a specified interval (ref)

x = np.linspace(0, 3.5, num=20) # default num = 50