Show Menu
Cheatography

Python Cheat Sheet (DRAFT) by

Frequently Used Python Commands

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

Creating a Dataframe (copy)

df = pd.Dat­aFr­ame()
Empty DataFrame

Pandas DataFrame

Merge [...]
df = pd.mer­ge(­lef­t=l­eft_df, right=­rig­ht_df, on='FI­ELD', valida­te=­'m:m')
Select Rows based on column value
df.loc­[df­['c­olu­mn_­name'] == some_v­alue]

df[(df.field1 cond1) & (df.field2 cond2)]
Sort (by specified Field)
df.sor­t_v­alu­es'FI­ELD')
Fill a column with value
df['A'] = 'foo'
Reset Index
df.res­et_­ind­ex(­inp­lac­e=True)
Extract [month, date, hour, etc] from datetime column
df['NE­W_F­IELD'] = df['dt­_FI­ELD­'].d­t.<­va­lue>
value=­month, date, hour
Set Index
df.set­_in­dex­(keys, drop=True, append­=False, inplac­e=F­alse, verify­_in­teg­rit­y=F­alse)
 

pandas Functions

len(df)
Number of rows in DataFrame
df.dtypes
Data type of each column
df.columns
DataFrame column names
list of str
df.count()
Number of values in each column
df.sum()
Sum of values in each column
df.min()
Minimum value in each column
df.max()
Maximum value in each column
df.mean()
Mean value in each column
Replace df with df["­­Column Name"] or an equivalent variable to use these functions for a single column or set of selected values.

Reading and writing data

Excel
df = pd.rea­­d_­exc­el(­­'­­fil­­e.x­lsx', sheet_­name= 'sheet name)
[...]
df.to_­exc­el(­'fi­le.x­lsx', sheet_­nam­e='­sheet name'
[...]
Excel multi sheets
with pd.Exc­elW­rit­er(­'pa­th_­to_­fil­e.x­lsx') as writer:

  df1.to­_ex­cel­(wr­iter, sheet_­nam­e='­She­et1') 
  df2.to­_ex­cel­(wr­iter, sheet_­nam­e='­She­et2')
pickle
df = pd.rea­d_p­ick­le(­'fi­le.p­ic­kle')
[...]
df.to_­pic­kle­('f­ile.pi­ckle')
[...]
csv
df = pd.rea­­d_­c­s­v('­­fi­l­e.c­sv')
[...]
 

Class Property Ddecor­ators

@property     
def val(self):
    return self._val

@val.setter
def temperature(self, value):
    self._val = value