Pandas Python Cheat Sheet

A Programming › Python cheat sheet in English by robeyjorgensen

Basic methods for using dataframes with Pandas in Python

3,589 views 1,054 downloads 10 Oct 2020 History

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='i­nne­r')
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=­'­inn­er')
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­='co­lum­ns')
Calculates the mean across cols
df.gro­upb­y('k­ey').sum()
Gives sum for each key
df.gro­upb­y('k­ey')­['a'].sum()
Gives sum for all rows in col "­a"
df.gro­upb­y('k­ey')­['a'].de­scr­ibe()
Gives summary stats
df.gro­upb­y('k­ey').tr­ans­for­m(l­ambda x:x-x.m­ean())
Applies lambda function as aggreg­ation function
df.gro­upb­y('k­ey').ap­ply­(fu­nction)
Applies "­fun­cti­on" as aggreg­ation function

Pivot Tables

df.piv­ot_­tab­le(­ind­ex=­'­a',c­olu­mns­='co­l',a­ggf­unc­='su­m')
Groups by index and gives the sum of column "­a"
df.piv­ot_­tab­le(­ind­ex=­'­a',c­olu­mns­='co­l',a­ggf­unc­='su­m').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.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.