Code Snippets
programming
Python
Code Snippets
hex string to int
int('000000007fff4070', base=16)
Matplotlib
List all fonts
def all_fonts():
return set([f.name for f in mpl.font_manager.fontManager.ttflist])
Three-dimensional surface plot
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import LightSource
= plt.figure()
fig = fig.gca(projection='3d')
ax
# Test data: Matlab `peaks()`
= np.mgrid[-3:3:150j,-3:3:150j]
x, y = 3*(1 - x)**2 * np.exp(-x**2 - (y + 1)**2) \
z - 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.
= LightSource(azdeg=0, altdeg=65)
ls # shade data, creating an rgb array.
= ls.shade(z, plt.cm.RdYlBu)
rgb = ax.plot_surface(x, y, z, rstride=1, cstride=1, linewidth=0,
surf =False, facecolors=rgb) antialiased
Pandas
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
retained.
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
= test_df()
df 'D'] = np.random.choice(list('ABCDE'), len(df))
df[# name=(col, func)
'D').agg(min_A=('A', np.min), one=('B', lambda x : 1))
df.groupby(
# col: ((name, func), ...)
'D').agg({'A':[['AMean', np.mean], ['ASum', np.sum]],
df.groupby('B':[['BMean', np.mean], ['BMin', np.min]]})
You an also do this:
import pandas as pd
# Sample data
= {
data 'payee': ['Payee1', 'Payee1', 'Payee2', 'Payee2', 'Payee3', 'Payee2'],
'account': ['Account1', 'Account1', 'Account2', 'Account3', 'Account1', 'Account2']
}= pd.DataFrame(data)
df
# Group by 'payee', then aggregate
= df.groupby('payee')['account'].agg(
result ='count',
Occurrences=lambda x: x.mode()[0],
ModeAccount=lambda x: (x == x.mode()[0]).sum()
ModeCount
).reset_index()
print(result)
WSL
- Access WSL files from Windows:
\\wsl$
- Access Windows files from WSL:
/mnt/c/
- Usually looking for
\\wsl$\Ubuntu\home\steve\.ipython\profile_default\startup