(Notes to myself about Python 3)

Pinboard: /u:kittell/t:python


Update pip (ref):
[Mac] pip install -U pip
[Windows] python -m pip install -U pip

Update package: pip install [package_name] --upgrade


Copy file: shutil.copy2(fullpath, fullpath_copy)

Delete file: os.remove(fullpath)

Read/write to files:

List/dict/set comprehensions

list_comp = [expr for val in collection if condition]
dict_comp = {key-expr : value-expr for value in collection if condition}
set_comp = {expr for value in collection if condition}

Operating system interfaces

os, os.path



Load workbook: wb = load_workbook(filename=fullpath, read_only=True)

Loop over rows in worksheet:

for row in ws.rows:
    for col in row:
        v = row[col].value


# Draw an ellipse using parametric equations
# Source:
import numpy
from matplotlib import pyplot
from math import pi
x_0 = 1.0
y_0 = 0.5
a = 2.0    # semimajor axis
b = 1.5    # semiminor axis
t = numpy.linspace(0, 2 * pi, 100)
pyplot.plot(x_0 + a * numpy.cos(t), y_0 + b * numpy.sin(t))

# Draw a random path

import numpy
import matplotlib.pyplot as pyplot

# Add random number of points
import random
n = random.randint(5,10)
points = numpy.zeros((n,2))

for i in range(n):
    # Add random points
    a = random.randint(1,10)
    b = random.randint(1,10)
    points[i,:] = [a, b]

# Complete the loop: repeat first point as last point
# Appending to numpy arrays:
points = numpy.append(points, [points[0,:]], axis=0)

pyplot.plot(points[:,0], points[:,1])


From Chris Moffitt, Tips for Selecting Columns in a DataFrame, Practical Business Python, 2019-11-26:

df = pd.read_csv(
col_mapping_dict = {c[0]:c[1] for c in enumerate(df.columns)}
df.iloc[:, np.r_[0:3,15:19,24,25]]