Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips and Traps¶
The Pythonic way of checking whether a collection (string, list, set, dict, etc.)
collis non-empty is to useif coll. However, do NOT useif arrto check whether a numpy array is non-empty or not. Instead, you shoule usearr.size >0to check whether a numpy array is non-empty or not.bottleneck is a collection of fast, NaN-aware NumPy array functions written in C.
from operator import itemgetter
import numpy as npConstruct Numpy Arrays¶
Construct a numpy array from a list.
arr = np.array([0, 1, 2, 3, 4, 5, 6])
arrarray([0, 1, 2, 3, 4, 5, 6])Join a sequence of arrays along a new axis using numpy.stack.
np.stack(
[
[1, 2, 3],
[4, 5, 6],
],
axis=0,
)np.stack(
[
[1, 2, 3],
[4, 5, 6],
],
axis=1,
)Slicing¶
arr[0]0arr[1:4]array([1, 2, 3])itemgetter(2, 3, 5)(arr)(2, 3, 5)numpy.flip¶
Reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered.
numpy.where¶
Note: numpy.where works on both numpy.ndarray and list,
however,
it doesn’t work on a generator/iterator.
arr = np.array([9, 80, 1, 2, 7, 1000])
arr >= 30array([False, True, False, False, False, True])np.where(arr >= 30)(array([1, 5]),)np.where(arr >= 30)[0].min()1np.min(np.where(arr >= 30))1numpy.ndarray.sum¶
arr.sum()21arr.prod()0Missing Values¶
np.NaN, np.NAN and np.nan are the same.
bottleneck is a collection of fast, NaN-aware NumPy array functions written in C.
np.NaN is np.NANTruenp.NAN is np.nanTrueMatrix¶
mat = np.matrix(
[
[1, 2, 3],
[4, 5, 6],
]
)mat.diagonal()matrix([[1, 5]])np.diag(mat)array([1, 5])