Show Menu
Cheatography

Numpy/Scipy Cheat Sheet (DRAFT) by

Variety of functions and useful things with a special focus on linear algebra/matricial stuff.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Libraries

Numpy
import numpy as np
Linear algebra (numpy)
import numpy.l­inalg as LA
Sparse operations (scipy)
import scipy.s­parse as ss
Sparse normal­iza­tions (sklearn)
from sklear­n.p­rep­roc­essing import normalize as sparse­_norm

Array compar­isons

Locate indices based on condition
index = np.whe­re(­array == 4)
Check if all/any satisfy condition
np.any­(array == 1), np.all­(array1 == array2)

Matricial operations

Dot product
np.dot(v1, v2)
or
v1 @ v2
Outer product
np.out­er(v1, v1)
Sum rows (0), columns (1)
np.sum(A, axis=0)
Eigenv­ector, eigenv­alues
eigval, eigvec = LA.eig(A)
The eigenv­ector output of the
eig()
function is a matrix containing the usual eigenv­ectors as its columns.

Numpy compar­isons

Check if any element satisfies a condition
np.any(A == 1)
Find which elements (their indices) satisfy a condition
np.where(A == 1)
Check if all elements satisfies a condition
np.all(A == 1)
Closeness up to tolerance
np.isc­los­e(1.001, 1)

Numpy utilities

Arrange all array elements in a list
np.rav­el(A)
 

Sparse matrices with scipy

Convert numpy matrices to sparse
A_sparse = ss.csr­_ma­trix(A) 
A_sparse = ss.csc­_ma­trix(A)
Change CSC to CSR and viceversa
A_csr = A_csc.t­ocsr() 
A_csc = A_csr.t­ocsc()
Row/col. normal­ization
A_norm = sparse­_no­rma­liz­e(A­_csc, norm='l1', axis=1)
Sparse identity matrix
sparse_id = ss.ide­nti­ty(n)
Invert a (CSC) sparse matrix
sparse_inv = ss.inv­(A_­sparse)
Dot product with vector
A_spar­se.d­ot(v)
Transpose sparse matrix
At_sparse = A_spar­se.t­ra­nsp­ose()
CSC (Compressed Sparse Column) are more suitable for column operations while CSR (Compressed Sparse Row) are for row operat­ions. For instance, row/col. normal­iza­tions.