Python packages


Info on some python packages.


numpy

Jargon

Axis parameter

https://stackoverflow.com/questions/48200911/very-basic-numpy-array-dimension-visualization

Stacking

>>> a = np.array([[1,0],[2,0],[3,0]])
>>> a
array([[1, 0],
       [2, 0],
       [3, 0]])

>>> np.hstack([a,a])
array([[1, 0, 1, 0],
       [2, 0, 2, 0],
       [3, 0, 3, 0]])

Matrix creation

Create a vector/matrix of all zeros

>>> np.zeros(3)
array([0., 0., 0.])

>>> np.zeros(3).shape
(3,)

>>> np.zeros(3).reshape(1,3)
array([[0., 0., 0.]])

>>> np.zeros(3).reshape(1,3).shape
(1, 3)

###

>>> np.zeros((1,3))
array([[0., 0., 0.]])

>>> np.zeros((1,3)).shape
(1, 3)

https://numpy.org/doc/stable/reference/generated/numpy.zeros.html

Make a matrix by giving all values explicitly

>>> np.array([[0, 1], [0, 0]])
array([[0, 1],
       [0, 0]])

Create a matrix out of a constant

>>> np.full((2,2), 3)
array([[3, 3],
       [3, 3]])

>>> np.full((2,2), np.inf)
array([[inf, inf],
       [inf, inf]])

>>> np.full((3,2), [1,2])
array([[1, 2],
       [1, 2],
       [1, 2]])

https://numpy.org/doc/stable/reference/generated/numpy.full.html

Matrix multiplication

Determinant of a matrix

Remember that determinant is not defined for non-square matrices.

>>> import numpy as np
>>> np.linalg.det(np.array([[1,2],
...                         [3,4]]))
...
-2.0000000000000004

https://numpy.org/doc/stable/reference/generated/numpy.linalg.det.html

Eigen values of a matrix

>>> np.linalg.eigvals(np.array([[1,2],
...                             [3,4]]))
...
array([-0.37228132,  5.37228132])

# Product of Eigen values is determinant
>>> np.prod(np.linalg.eigvals(np.array([[1,2],[3,4]])))
-1.9999999999999998

https://numpy.org/doc/stable/reference/generated/numpy.linalg.eigvals.html

Doubts

Misc

Theory

Pandas

Merge two Series to make a DataFrame

>>> pd.concat([s1, s2], axis=1)

>>> pd.concat([s1, s2], axis=1).columns
RangeIndex(start=0, stop=2, step=1)

Examples

# Read from a csv file
>>> df = pd.read_csv("name.csv")

# Columns
>>> df.columns
Index(['Site Type', 'Used', 'Fixed', 'Prohibited', 'Available', 'Util%'], dtype='object')

# Number of rows
>>> a.index
RangeIndex(start=0, stop=16, step=1)

scipy

Sparse matrix

https://docs.scipy.org/doc/scipy/reference/sparse.html

>>> import scipy
>>> import numpy as np
>>> X = scipy.sparse.csr_matrix(1./2.*np.array([[0.,1.],[1.,0.]]))

>>> X
<2x2 sparse matrix of type '<class 'numpy.float64'>'
        with 2 stored elements in Compressed Sparse Row format>

>>> print(X)
  (0, 1)        0.5
  (1, 0)        0.5

networkx

Graph attributes

Add nodes

Add edges

Adding edges implicitly adds nodes.

BeautifulSoup4

https://www.crummy.com/software/BeautifulSoup/bs4/doc/

import pathlib
from bs4 import BeautifulSoup

html_path = pathlib.Path("/home/user/Downloads/input.html")
htmlstr = html_path.read_text()
soup = BeautifulSoup(htmlstr)
content = soup.find(id='content-container')

Finding

Children

conda

More packages

Tools: