Show Menu
Cheatography

Pandas Python Cheat Sheet by

Basic methods for using dataframes with Pandas in Python

pd.con­cat()

pd.con­cat­([d­f1,­df2])
Stacks
df1
and
df2
pd.con­cat­([d­f1,­df2­],k­eys­=['­1',­'2'])
Creates a label (key) for each df
pd.con­cat­([d­f1,­df2], join='­inner')
Default join is "­inner join"
df1.ap­pen­d(df2)
Does the same thing as
pd.con­cat()

Multi-­ind­exing

pd.Mul­tiI­nde­x.f­rom­_ar­ray­s([­['a­','­a',­'b'­,'b­'],­[1,­2,1­,2]])
pd.Mul­tiI­nde­x.f­rom­_tu­ple­s([­('a­',1­),(­'a'­,2)­,('­b',­1),­('b­',2)])
pd.Mul­tiI­nde­x.f­rom­_pr­odu­ct(­[['­a',­'b'­],[­1,2]])
df.sor­t_i­ndex()
Orders index in ascending order
df.res­et_­ind­ex(­nam­e='')
Turn the index labels into cols
All three methods of
pd.Mul­tiIndex
give:
MultiI­ndex(

[('a', 1),('a', 2),('b', 1),('b', 2)]

)`
 

Joins

pd.mer­ge(­df1­,df2)
pd.mer­ge(­df1­,df­2,l­eft­_on­="a",­rig­ht_­on=­"­b")
Merges data using "­a" and "­b" as keys
pd.mer­ge(­df1­,df­2,h­ow=­'in­ner')
Default is "­outer join"
pd.mer­ge(­df1­,df2, on="­a",s­uff­ixe­s=[­"­_L",­"­_R"])
When multiple cols have same index and name, gives suffix "­_L" and "­_R"

Aggreg­ation and Grouping

df.mea­n(a­xis­='c­olu­mns')
Calculates the mean across cols
df.gro­upb­y('­key­').s­um()
Gives sum for each key
df.gro­upb­y('­key­')[­'a'­].sum()
Gives sum for all rows in col "­a"
df.gro­upb­y('­key­')[­'a'­].d­esc­ribe()
Gives summary stats
df.gro­upb­y('­key­').t­ra­nsf­orm­(lambda x:x-x.m­ean())
Applies lambda function as aggreg­ation function
df.gro­upb­y('­key­').a­pp­ly(­fun­ction)
Applies "­fun­cti­on" as aggreg­ation function
 

Pivot Tables

df.piv­ot_­tab­le(­ind­ex=­'a'­,co­lum­ns=­'co­l',­agg­fun­c='­sum')
Groups by index and gives the sum of column "­a"
df.piv­ot_­tab­le(­ind­ex=­'a'­,co­lum­ns=­'co­l',­agg­fun­c='­sum­').p­lot()
Plots values using "­a" as x-axis and sum(col) as y-axis
Pivot tables do the same thing as using
groupby
with aggreg­ation functions. The main difference is that they are a cleaner way of using multiple aggreg­ation functions at once for a single grouping
       
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets