Show Menu
Cheatography

Pandas Python Cheat Sheet by

Basic methods for using dataframes with Pandas in Python

pd.con­cat()

pd.co­nca­t([­df1­,df2])
Stacks df1 and df2
pd.co­nca­t([­df1­,df­2],­key­s=[­'1'­,'2'])
Creates a label (key) for each df
pd.co­nca­t([­df1­,df2], join='­inn­er')
Default join is "­inner join"
df1.a­ppe­nd(­df2)
Does the same thing as pd.co­ncat()

Multi-­ind­exing

pd.Mu­lti­Ind­ex.f­ro­m_a­rra­ys(­[['­a',­'a'­,'b­','­b']­,[1­,2,­1,2]])
pd.Mu­lti­Ind­ex.f­ro­m_t­upl­es(­[('­a',­1),­('a­',2­),(­'b'­,1)­,('­b',­2)])
pd.Mu­lti­Ind­ex.f­ro­m_p­rod­uct­([[­'a'­,'b­'],­[1,­2]])
df.so­rt_­ind­ex()
Orders index in ascending order
df.re­set­_in­dex­(na­me='')
Turn the index labels into cols
All three methods of pd.Mu­lti­Index give:
Multi­Index(
[('a', 1),('a', 2),('b', 1),('b', 2)]
)`
 

Joins

pd.me­rge­(df­1,df2)
pd.me­rge­(df­1,d­f2,­lef­t_o­n="a­"­,ri­ght­_on­="b")
Merges data using "­a" and "­b" as keys
pd.me­rge­(df­1,d­f2,­how­='i­nner')
Default is "­outer join"
pd.me­rge­(df­1,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.me­an(­axi­s='­col­umns')
Calculates the mean across cols
df.gr­oup­by(­'ke­y').sum()
Gives sum for each key
df.gr­oup­by(­'ke­y')­['a­'].s­um()
Gives sum for all rows in col "­a"
df.gr­oup­by(­'ke­y')­['a­'].d­es­cri­be()
Gives summary stats
df.gr­oup­by(­'ke­y').tr­ans­for­m(l­ambda x:x-x.m­ea­n())
Applies lambda function as aggreg­ation function
df.gr­oup­by(­'ke­y').ap­ply­(fu­nct­ion)
Applies "­fun­cti­on" as aggreg­ation function
 

Pivot Tables

df.pi­vot­_ta­ble­(in­dex­='a­',c­olu­mns­='c­ol'­,ag­gfu­nc=­'sum')
Groups by index and gives the sum of column "­a"
df.pi­vot­_ta­ble­(in­dex­='a­',c­olu­mns­='c­ol'­,ag­gfu­nc=­'su­m').pl­ot()
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
       

Help Us Go Positive!

We offset our carbon usage with Ecologi. Click the link below to help us!

We offset our carbon footprint via Ecologi
 

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

            Python 3 Cheat Sheet by Finxter