Code Snippets

Computer Setup

  • Add to PATH variable: single location (\S\bin) for personal scripts
    • includes publish.bat script
  • Add to PYTHONPATH variable: current projects
    • …TELOS\Python\GREAT_project;
    • …TELOS\Python\cartogram_project\scratch;
    • …TELOS\Python\meta_reddit
    • …TELOS\Blog\Python;


Script to publish blog post

python -m blog_tools -u -a post_file -f %1 2>&1

REM reset site


hex string to int

int('000000007fff4070', base=16)

Common imports

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from great import test_df


List all fonts

def all_fonts():
    return set([ for f in mpl.font_manager.fontManager.ttflist])

Three-dimensional surface plot

from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import LightSource

fig = plt.figure()
ax = fig.gca(projection='3d')

# Test data: Matlab `peaks()`
x, y = np.mgrid[-3:3:150j,-3:3:150j]
z =  3*(1 - x)**2 * np.exp(-x**2 - (y + 1)**2) \
   - 10*(x/5 - x**3 - y**5)*np.exp(-x**2 - y**2) \
   - 1./3*np.exp(-(x + 1)**2 - y**2)

# create light source object.
ls = LightSource(azdeg=0, altdeg=65)
# shade data, creating an rgb array.
rgb = ls.shade(z,
surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, linewidth=0,
                       antialiased=False, facecolors=rgb)


apply expanding output

Use result_type argument to apply.

result_type : {‘expand’, ‘reduce’, ‘broadcast’, None}, default None These only act when axis=1 (columns):

   * 'expand' : list-like results will be turned into columns.
   * 'reduce' : returns a Series if possible rather than expanding
     list-like results. This is the opposite of 'expand'.
   * 'broadcast' : results will be broadcast to the original shape
     of the DataFrame, the original index and columns will be

   The default behaviour (None) depends on the return value of the
   applied function: list-like results will be returned as a Series
   of those. However if the apply function returns a Series these
   are expanded to columns.

Named functions and columns in agg

df = test_df()
df['D'] = np.random.choice(list('ABCDE'), len(df))
# name=(col, func)
df.groupby('D').agg(min_A=('A', np.min), one=('B', lambda x : 1))

# col: ((name, func), ...)
df.groupby('D').agg({'A':[['AMean', np.mean], ['ASum', np.sum]],
                     'B':[['BMean', np.mean], ['BMin', np.min]]})


  • Access WSL files from Windows: \\wsl$
  • Access Windows files from WSL: /mnt/c/
  • Usually looking for \\wsl$\Ubuntu\home\steve\.ipython\profile_default\startup

posted 2022-02-02 | tags: programming, code, Python

Share on