Python Fundamentals
List/Dictionary/Set Comprehension
<new-list-name> = [ <expression> for <element> in <list-name> if <condition> ]
Class
- private instance variable by adding
__before variable’s name, e.g.self.__x - class variable changes across object of the same class, e.g.
Class.x
NumPy
Integer Array Indexing
a = np.array([[1,2], [3, 4], [5, 6]])
# An example of integer array indexing.
# The returned array will have shape (3,) and
print(a[[0, 1, 2], [0, 1, 0]]) # Prints "[1 4 5]"- Returns an copied 1D array
- Elements can be reused
- Math operators (e.g.
+=) for mutating each indexed element
Boolean Array Indexing
Data Types
https://numpy.org/doc/stable/reference/arrays.dtypes.html#arrays-dtypes-constructing
New Axis
arr[np.newaxis] or arr[None]
- Specify new axis position by
arr[:, np.newaxis, :], put colon at where axis remains the same- Or
np.expand_dims(arr, <after_this_dimension>)
- Or
- Added to the front, e.g.
(5, )will become(1, 5)
Broadcasting
np.array([1, 2, 3]) is (3, )
np.array([2]) is (1, )
- Compare shape of array from right to left
- Prepend 1 to shape if rank is not the same
- Broadcasting is doable if all dimensions is compatible (same or either one is 1)
Important
p. 80-82, 87-88
https://www.pythonlikeyoumeanit.com/Module3_IntroducingNumpy/Broadcasting.html
Centering
- Calculate mean of columns
arr.mean(<dimension>) - Subtract mean from each entry to obtain the centered array
Pairwise Distances
https://stackoverflow.com/a/37903795
Cheatsheets
np.array(<list>)
np.zeros(<shape>)
np.ones(<shape>)
np.arange(<range>)
np.linspace(start=, stop=, num=)
np.logspace(start=, stop=, num=)
<arr2> = <arr1>.copy()<arr>.shape
<arr>.ndim
<arr>.size