Show Menu
Cheatography

Python Cheatsheet Cheat Sheet (DRAFT) by

Basic python cheatsheet

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

Useful Shortcuts

Control Q
access docume­ntation
Control D
duplicate code block
dir()
see the list of methods
Tab (in Git bash)
to toggle the files in the directory

Useful OS commands

os.get­cwd()
get current directory
os.chd­ir(­'path')
change directory
os.lis­tdi­r('­fol­der­_path')
list directory
os.pat­h.j­oin­('p­ath1', 'path2')
join file path

Set up Env

conda env create --prefix P:\env­\myenv --file­='P­:\f­ile­pat­h\e­nv.yml'
conda create env_name
create a new env
pip install -r "­P:­\fil­epa­th­\req­uir­eme­nts.tx­t"
pip install 'P:\fi­lep­ath­\pa­cka­ge.whl' --forc­e-r­ein­stall
reinstall whl file

Pandas Display

pd.set­_op­tio­n(‘­dis­pla­y.m­ax_­col­width’, 10_000)
pd.set­_op­tio­n(‘­dis­pla­y.m­ax_­rows’, 1000)
ps.set­_op­tio­n('­dis­pla­y.m­ax_­col­umns', 100)

Neat Functions

[funct­ion(i) for i in list if logic_­exp­res­sion]
list compre­hension
lambda arguments: expression
(e.g.) x = lambda a, b : a * b
print(x(5, 6))
a lambda function is a small anonymous function

Explore data

df.col.de­scr­ibe()
df.col.va­lue­_co­unts()
normal­ize­=True
 

Reshape dataframe

df.gro­upb­y('­col­1').co­l2.c­ount()
count / sum / min / max / mean
df.gro­upb­y([­'col1', 'col2'­]).[­'c­ol3', 'col4'­].c­ount()
df1 = df.gro­upb­y('­col­').a­gg­({'­val­ue1­':[­'mi­n',­'max'], 'value­2':­['m­ean']})
df.piv­ot_­table(index='col1', columns='col2', values=['col3', 'col4'], aggfunc={'col­3':­np.m­ean, 'col4'­:[min, max]})
df1.co­lumns = ['_'.j­oin­(col) for col in df1.co­lumns]
to flatten multi index df after groupby / pivot
df1.me­rge­(df2, left_o­n='­l_key', right_­on=­'r_­key', how='l­eft')
how: {‘left’, ‘right’, ‘outer’, ‘inner’, ‘cross’}, default ‘inner’
pd.con­cat­([df1, df2])
union 2 dataframes

Statements

For Loop
for var in range: 
 sta­tements
While Loop
while expres­sion: 
  ­sta­t­ements
If Statement
if expres­sion: ­
 sta­tements
elif expres­sion: ­ ­
 sta­tements
else:
 ­sta­tements
Exception Handling
try: 
  print(x)
except NameError:
  print(­"­var­iable x is not define­d")
except:
  print(­"sth else went wrong")
else:
  print(­"nth went wrong")
finally:
  print(­"the 'try except' is finish­ed")