SlideShare a Scribd company logo
1 of 2
Download to read offline
F M A
Data Wrangling
with pandas
Cheat Sheet
http://pandas.pydata.org
Syntax – Creating DataFrames
Tidy Data – A foundation for wrangling in pandas
In a tidy
data set:
F M A
Each variable is saved
in its own column
&Each observation is
saved in its own row
Tidy data complements pandas’s vectorized
operations. pandas will automatically preserve
observations as you manipulate variables. No
other format works as intuitively with pandas.
Reshaping Data – Change the layout of a data set
M A F
*
M A*
pd.melt(df)
Gather columns into rows.
df.pivot(columns='var', values='val')
Spread rows into columns.
pd.concat([df1,df2])
Append rows of DataFrames
pd.concat([df1,df2], axis=1)
Append columns of DataFrames
df.sort_values('mpg')
Order rows by values of a column (low to high).
df.sort_values('mpg',ascending=False)
Order rows by values of a column (high to low).
df.rename(columns = {'y':'year'})
Rename the columns of a DataFrame
df.sort_index()
Sort the index of a DataFrame
df.reset_index()
Reset index of DataFrame to row numbers, moving
index to columns.
df.drop(columns=['Length','Height'])
Drop columns from DataFrame
Subset Observations (Rows) Subset Variables (Columns)
a b c
1 4 7 10
2 5 8 11
3 6 9 12
df = pd.DataFrame(
{"a" : [4 ,5, 6],
"b" : [7, 8, 9],
"c" : [10, 11, 12]},
index = [1, 2, 3])
Specify values for each column.
df = pd.DataFrame(
[[4, 7, 10],
[5, 8, 11],
[6, 9, 12]],
index=[1, 2, 3],
columns=['a', 'b', 'c'])
Specify values for each row.
a b c
n v
d
1 4 7 10
2 5 8 11
e 2 6 9 12
df = pd.DataFrame(
{"a" : [4 ,5, 6],
"b" : [7, 8, 9],
"c" : [10, 11, 12]},
index = pd.MultiIndex.from_tuples(
[('d',1),('d',2),('e',2)],
names=['n','v']))
Create DataFrame with a MultiIndex
Method Chaining
Most pandas methods return a DataFrame so that
another pandas method can be applied to the
result. This improves readability of code.
df = (pd.melt(df)
.rename(columns={
'variable' : 'var',
'value' : 'val'})
.query('val >= 200')
)
df[df.Length > 7]
Extract rows that meet logical
criteria.
df.drop_duplicates()
Remove duplicate rows (only
considers columns).
df.head(n)
Select first n rows.
df.tail(n)
Select last n rows.
Logic in Python (and pandas)
< Less than != Not equal to
> Greater than df.column.isin(values) Group membership
== Equals pd.isnull(obj) Is NaN
<= Less than or equals pd.notnull(obj) Is not NaN
>= Greater than or equals &,|,~,^,df.any(),df.all() Logical and, or, not, xor, any, all
http://pandas.pydata.org/ This cheat sheet inspired by Rstudio Data Wrangling Cheatsheet (https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf) Written by Irv Lustig, Princeton Consultants
df[['width','length','species']]
Select multiple columns with specific names.
df['width'] or df.width
Select single column with specific name.
df.filter(regex='regex')
Select columns whose name matches regular expression regex.
df.loc[:,'x2':'x4']
Select all columns between x2 and x4 (inclusive).
df.iloc[:,[1,2,5]]
Select columns in positions 1, 2 and 5 (first column is 0).
df.loc[df['a'] > 10, ['a','c']]
Select rows meeting logical condition, and only the specific columns .
regex (Regular Expressions) Examples
'.' Matches strings containing a period '.'
'Length$' Matches strings ending with word 'Length'
'^Sepal' Matches strings beginning with the word 'Sepal'
'^x[1-5]$' Matches strings beginning with 'x' and ending with 1,2,3,4,5
'^(?!Species$).*' Matches strings except the string 'Species'
df.sample(frac=0.5)
Randomly select fraction of rows.
df.sample(n=10)
Randomly select n rows.
df.iloc[10:20]
Select rows by position.
df.nlargest(n, 'value')
Select and order top n entries.
df.nsmallest(n, 'value')
Select and order bottom n entries.
Summarize Data
Make New Columns
Combine Data Sets
df['w'].value_counts()
Count number of rows with each unique value of variable
len(df)
# of rows in DataFrame.
df['w'].nunique()
# of distinct values in a column.
df.describe()
Basic descriptive statistics for each column (or GroupBy)
pandas provides a large set of summary functions that operate on
different kinds of pandas objects (DataFrame columns, Series,
GroupBy, Expanding and Rolling (see below)) and produce single
values for each of the groups. When applied to a DataFrame, the
result is returned as a pandas Series for each column. Examples:
sum()
Sum values of each object.
count()
Count non-NA/null values of
each object.
median()
Median value of each object.
quantile([0.25,0.75])
Quantiles of each object.
apply(function)
Apply function to each object.
min()
Minimum value in each object.
max()
Maximum value in each object.
mean()
Mean value of each object.
var()
Variance of each object.
std()
Standard deviation of each
object.
df.assign(Area=lambda df: df.Length*df.Height)
Compute and append one or more new columns.
df['Volume'] = df.Length*df.Height*df.Depth
Add single column.
pd.qcut(df.col, n, labels=False)
Bin column into n buckets.
Vector
function
Vector
function
pandas provides a large set of vector functions that operate on all
columns of a DataFrame or a single selected column (a pandas
Series). These functions produce vectors of values for each of the
columns, or a single Series for the individual Series. Examples:
shift(1)
Copy with values shifted by 1.
rank(method='dense')
Ranks with no gaps.
rank(method='min')
Ranks. Ties get min rank.
rank(pct=True)
Ranks rescaled to interval [0, 1].
rank(method='first')
Ranks. Ties go to first value.
shift(-1)
Copy with values lagged by 1.
cumsum()
Cumulative sum.
cummax()
Cumulative max.
cummin()
Cumulative min.
cumprod()
Cumulative product.
x1 x2
A 1
B 2
C 3
x1 x3
A T
B F
D T
adf bdf
Standard Joins
x1 x2 x3
A 1 T
B 2 F
C 3 NaN
x1 x2 x3
A 1.0 T
B 2.0 F
D NaN T
x1 x2 x3
A 1 T
B 2 F
x1 x2 x3
A 1 T
B 2 F
C 3 NaN
D NaN T
pd.merge(adf, bdf,
how='left', on='x1')
Join matching rows from bdf to adf.
pd.merge(adf, bdf,
how='right', on='x1')
Join matching rows from adf to bdf.
pd.merge(adf, bdf,
how='inner', on='x1')
Join data. Retain only rows in both sets.
pd.merge(adf, bdf,
how='outer', on='x1')
Join data. Retain all values, all rows.
Filtering Joins
x1 x2
A 1
B 2
x1 x2
C 3
adf[adf.x1.isin(bdf.x1)]
All rows in adf that have a match in bdf.
adf[~adf.x1.isin(bdf.x1)]
All rows in adf that do not have a match in bdf.
x1 x2
A 1
B 2
C 3
x1 x2
B 2
C 3
D 4
ydf zdf
Set-like Operations
x1 x2
B 2
C 3
x1 x2
A 1
B 2
C 3
D 4
x1 x2
A 1
pd.merge(ydf, zdf)
Rows that appear in both ydf and zdf
(Intersection).
pd.merge(ydf, zdf, how='outer')
Rows that appear in either or both ydf and zdf
(Union).
pd.merge(ydf, zdf, how='outer',
indicator=True)
.query('_merge == "left_only"')
.drop(columns=['_merge'])
Rows that appear in ydf but not zdf (Setdiff).
Group Data
df.groupby(by="col")
Return a GroupBy object,
grouped by values in column
named "col".
df.groupby(level="ind")
Return a GroupBy object,
grouped by values in index
level named "ind".
All of the summary functions listed above can be applied to a group.
Additional GroupBy functions:
max(axis=1)
Element-wise max.
clip(lower=-10,upper=10)
Trim values at input thresholds
min(axis=1)
Element-wise min.
abs()
Absolute value.
The examples below can also be applied to groups. In this case, the
function is applied on a per-group basis, and the returned vectors
are of the length of the original DataFrame.
Windows
df.expanding()
Return an Expanding object allowing summary functions to be
applied cumulatively.
df.rolling(n)
Return a Rolling object allowing summary functions to be
applied to windows of length n.
size()
Size of each group.
agg(function)
Aggregate group using function.
Handling Missing Data
df.dropna()
Drop rows with any column having NA/null data.
df.fillna(value)
Replace all NA/null data with value.
Plotting
df.plot.hist()
Histogram for each column
df.plot.scatter(x='w',y='h')
Scatter chart using pairs of points
http://pandas.pydata.org/ This cheat sheet inspired by Rstudio Data Wrangling Cheatsheet (https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf) Written by Irv Lustig, Princeton Consultants

More Related Content

What's hot

Spark Summit EU talk by Ted Malaska
Spark Summit EU talk by Ted MalaskaSpark Summit EU talk by Ted Malaska
Spark Summit EU talk by Ted MalaskaSpark Summit
 
Introduction to redis
Introduction to redisIntroduction to redis
Introduction to redisTanu Siwag
 
Triplestore and SPARQL
Triplestore and SPARQLTriplestore and SPARQL
Triplestore and SPARQLLino Valdivia
 
Data visualization using R
Data visualization using RData visualization using R
Data visualization using RUmmiya Mohammedi
 
Pandas Cheat Sheet
Pandas Cheat SheetPandas Cheat Sheet
Pandas Cheat SheetACASH1011
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to RedisArnab Mitra
 
Unit 2 - Data Manipulation with R.pptx
Unit 2 - Data Manipulation with R.pptxUnit 2 - Data Manipulation with R.pptx
Unit 2 - Data Manipulation with R.pptxMalla Reddy University
 
Caching solutions with Redis
Caching solutions   with RedisCaching solutions   with Redis
Caching solutions with RedisGeorge Platon
 
9. Document Oriented Databases
9. Document Oriented Databases9. Document Oriented Databases
9. Document Oriented DatabasesFabio Fumarola
 
Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet Dr. Volkan OBAN
 
Chapter 04-discriminant analysis
Chapter 04-discriminant analysisChapter 04-discriminant analysis
Chapter 04-discriminant analysisRaman Kannan
 
Resource Bundle
Resource BundleResource Bundle
Resource BundleSunil OS
 
Hadoop Query Performance Smackdown
Hadoop Query Performance SmackdownHadoop Query Performance Smackdown
Hadoop Query Performance SmackdownDataWorks Summit
 

What's hot (20)

Spark Summit EU talk by Ted Malaska
Spark Summit EU talk by Ted MalaskaSpark Summit EU talk by Ted Malaska
Spark Summit EU talk by Ted Malaska
 
Introduction to sqoop
Introduction to sqoopIntroduction to sqoop
Introduction to sqoop
 
Introduction to redis
Introduction to redisIntroduction to redis
Introduction to redis
 
Hbase
HbaseHbase
Hbase
 
Triplestore and SPARQL
Triplestore and SPARQLTriplestore and SPARQL
Triplestore and SPARQL
 
Data visualization using R
Data visualization using RData visualization using R
Data visualization using R
 
Pandas Cheat Sheet
Pandas Cheat SheetPandas Cheat Sheet
Pandas Cheat Sheet
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
Unit 2 - Data Manipulation with R.pptx
Unit 2 - Data Manipulation with R.pptxUnit 2 - Data Manipulation with R.pptx
Unit 2 - Data Manipulation with R.pptx
 
Dapper
DapperDapper
Dapper
 
NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
 
Event-sourced architectures with Akka
Event-sourced architectures with AkkaEvent-sourced architectures with Akka
Event-sourced architectures with Akka
 
Caching solutions with Redis
Caching solutions   with RedisCaching solutions   with Redis
Caching solutions with Redis
 
9. Document Oriented Databases
9. Document Oriented Databases9. Document Oriented Databases
9. Document Oriented Databases
 
Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet Python Pandas for Data Science cheatsheet
Python Pandas for Data Science cheatsheet
 
Chapter 04-discriminant analysis
Chapter 04-discriminant analysisChapter 04-discriminant analysis
Chapter 04-discriminant analysis
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
 
Sqoop
SqoopSqoop
Sqoop
 
Hadoop Query Performance Smackdown
Hadoop Query Performance SmackdownHadoop Query Performance Smackdown
Hadoop Query Performance Smackdown
 

Similar to Pandas cheat sheet_data science

Pandas,scipy,numpy cheatsheet
Pandas,scipy,numpy cheatsheetPandas,scipy,numpy cheatsheet
Pandas,scipy,numpy cheatsheetDr. Volkan OBAN
 
pandas dataframe notes.pdf
pandas dataframe notes.pdfpandas dataframe notes.pdf
pandas dataframe notes.pdfAjeshSurejan2
 
Cheat Sheet for Stata v15.00 PDF Complete
Cheat Sheet for Stata v15.00 PDF CompleteCheat Sheet for Stata v15.00 PDF Complete
Cheat Sheet for Stata v15.00 PDF CompleteTsamaraLuthfia1
 
Stata Cheat Sheets (all)
Stata Cheat Sheets (all)Stata Cheat Sheets (all)
Stata Cheat Sheets (all)Laura Hughes
 
R Cheat Sheet – Data Management
R Cheat Sheet – Data ManagementR Cheat Sheet – Data Management
R Cheat Sheet – Data ManagementDr. Volkan OBAN
 
Pandas Dataframe reading data Kirti final.pptx
Pandas Dataframe reading data  Kirti final.pptxPandas Dataframe reading data  Kirti final.pptx
Pandas Dataframe reading data Kirti final.pptxKirti Verma
 
wk5ppt1_Titanic
wk5ppt1_Titanicwk5ppt1_Titanic
wk5ppt1_TitanicAliciaWei1
 
Broom: Converting Statistical Models to Tidy Data Frames
Broom: Converting Statistical Models to Tidy Data FramesBroom: Converting Statistical Models to Tidy Data Frames
Broom: Converting Statistical Models to Tidy Data FramesWork-Bench
 
Pandas pythonfordatascience
Pandas pythonfordatasciencePandas pythonfordatascience
Pandas pythonfordatascienceNishant Upadhyay
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processingTim Essam
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional ProgrammingEelco Visser
 
Unit 4_Working with Graphs _python (2).pptx
Unit 4_Working with Graphs _python (2).pptxUnit 4_Working with Graphs _python (2).pptx
Unit 4_Working with Graphs _python (2).pptxprakashvs7
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationEelco Visser
 
Python-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxPython-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxParveenShaik21
 

Similar to Pandas cheat sheet_data science (20)

Pandas,scipy,numpy cheatsheet
Pandas,scipy,numpy cheatsheetPandas,scipy,numpy cheatsheet
Pandas,scipy,numpy cheatsheet
 
pandas dataframe notes.pdf
pandas dataframe notes.pdfpandas dataframe notes.pdf
pandas dataframe notes.pdf
 
Cheat Sheet for Stata v15.00 PDF Complete
Cheat Sheet for Stata v15.00 PDF CompleteCheat Sheet for Stata v15.00 PDF Complete
Cheat Sheet for Stata v15.00 PDF Complete
 
Stata Cheat Sheets (all)
Stata Cheat Sheets (all)Stata Cheat Sheets (all)
Stata Cheat Sheets (all)
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
interenship.pptx
interenship.pptxinterenship.pptx
interenship.pptx
 
Practical cats
Practical catsPractical cats
Practical cats
 
R Cheat Sheet – Data Management
R Cheat Sheet – Data ManagementR Cheat Sheet – Data Management
R Cheat Sheet – Data Management
 
Pandas Dataframe reading data Kirti final.pptx
Pandas Dataframe reading data  Kirti final.pptxPandas Dataframe reading data  Kirti final.pptx
Pandas Dataframe reading data Kirti final.pptx
 
Python for R users
Python for R usersPython for R users
Python for R users
 
wk5ppt1_Titanic
wk5ppt1_Titanicwk5ppt1_Titanic
wk5ppt1_Titanic
 
Broom: Converting Statistical Models to Tidy Data Frames
Broom: Converting Statistical Models to Tidy Data FramesBroom: Converting Statistical Models to Tidy Data Frames
Broom: Converting Statistical Models to Tidy Data Frames
 
Data transformation-cheatsheet
Data transformation-cheatsheetData transformation-cheatsheet
Data transformation-cheatsheet
 
Pandas pythonfordatascience
Pandas pythonfordatasciencePandas pythonfordatascience
Pandas pythonfordatascience
 
2 pandasbasic
2 pandasbasic2 pandasbasic
2 pandasbasic
 
Stata cheat sheet: data processing
Stata cheat sheet: data processingStata cheat sheet: data processing
Stata cheat sheet: data processing
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Unit 4_Working with Graphs _python (2).pptx
Unit 4_Working with Graphs _python (2).pptxUnit 4_Working with Graphs _python (2).pptx
Unit 4_Working with Graphs _python (2).pptx
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type Parameterization
 
Python-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptxPython-for-Data-Analysis.pptx
Python-for-Data-Analysis.pptx
 

Recently uploaded

一比一原版(UCD毕业证书)都柏林大学毕业证成绩单原件一模一样
一比一原版(UCD毕业证书)都柏林大学毕业证成绩单原件一模一样一比一原版(UCD毕业证书)都柏林大学毕业证成绩单原件一模一样
一比一原版(UCD毕业证书)都柏林大学毕业证成绩单原件一模一样dyuozua
 
Dubai Call Girls/// Hot Afternoon O525547819 Call Girls In Dubai
Dubai Call Girls/// Hot Afternoon O525547819 Call Girls In DubaiDubai Call Girls/// Hot Afternoon O525547819 Call Girls In Dubai
Dubai Call Girls/// Hot Afternoon O525547819 Call Girls In Dubaikojalkojal131
 
Camil Institutional Presentation_Mai24.pdf
Camil Institutional Presentation_Mai24.pdfCamil Institutional Presentation_Mai24.pdf
Camil Institutional Presentation_Mai24.pdfCAMILRI
 
一比一原版(UoA毕业证书)奥克兰大学毕业证成绩单原件一模一样
一比一原版(UoA毕业证书)奥克兰大学毕业证成绩单原件一模一样一比一原版(UoA毕业证书)奥克兰大学毕业证成绩单原件一模一样
一比一原版(UoA毕业证书)奥克兰大学毕业证成绩单原件一模一样dyuozua
 
Gorakhpur Call Girls 8250092165 Low Price Escorts Service in Your Area
Gorakhpur Call Girls 8250092165 Low Price Escorts Service in Your AreaGorakhpur Call Girls 8250092165 Low Price Escorts Service in Your Area
Gorakhpur Call Girls 8250092165 Low Price Escorts Service in Your Areameghakumariji156
 
一比一原版(EUR毕业证书)鹿特丹伊拉斯姆斯大学毕业证原件一模一样
一比一原版(EUR毕业证书)鹿特丹伊拉斯姆斯大学毕业证原件一模一样一比一原版(EUR毕业证书)鹿特丹伊拉斯姆斯大学毕业证原件一模一样
一比一原版(EUR毕业证书)鹿特丹伊拉斯姆斯大学毕业证原件一模一样sovco
 
The Leonardo 1Q 2024 Results Presentation
The Leonardo 1Q 2024 Results PresentationThe Leonardo 1Q 2024 Results Presentation
The Leonardo 1Q 2024 Results PresentationLeonardo
 
一比一原版(Waikato毕业证书)怀卡托大学毕业证成绩单原件一模一样
一比一原版(Waikato毕业证书)怀卡托大学毕业证成绩单原件一模一样一比一原版(Waikato毕业证书)怀卡托大学毕业证成绩单原件一模一样
一比一原版(Waikato毕业证书)怀卡托大学毕业证成绩单原件一模一样dyuozua
 
一比一原版(AUT毕业证书)奥克兰理工大学毕业证成绩单原件一模一样
一比一原版(AUT毕业证书)奥克兰理工大学毕业证成绩单原件一模一样一比一原版(AUT毕业证书)奥克兰理工大学毕业证成绩单原件一模一样
一比一原版(AUT毕业证书)奥克兰理工大学毕业证成绩单原件一模一样dyuozua
 
Western Copper and Gold - May 2024 Presentation
Western Copper and Gold - May 2024 PresentationWestern Copper and Gold - May 2024 Presentation
Western Copper and Gold - May 2024 PresentationPaul West-Sells
 
一比一原版(VUW毕业证书)惠灵顿维多利亚大学毕业证成绩单原件一模一样
一比一原版(VUW毕业证书)惠灵顿维多利亚大学毕业证成绩单原件一模一样一比一原版(VUW毕业证书)惠灵顿维多利亚大学毕业证成绩单原件一模一样
一比一原版(VUW毕业证书)惠灵顿维多利亚大学毕业证成绩单原件一模一样dyuozua
 
一比一原版(MU毕业证书)梅努斯大学毕业证成绩单原件一模一样
一比一原版(MU毕业证书)梅努斯大学毕业证成绩单原件一模一样一比一原版(MU毕业证书)梅努斯大学毕业证成绩单原件一模一样
一比一原版(MU毕业证书)梅努斯大学毕业证成绩单原件一模一样dyuozua
 
一比一原版(Galway毕业证书)爱尔兰高威大学毕业证成绩单原件一模一样
一比一原版(Galway毕业证书)爱尔兰高威大学毕业证成绩单原件一模一样一比一原版(Galway毕业证书)爱尔兰高威大学毕业证成绩单原件一模一样
一比一原版(Galway毕业证书)爱尔兰高威大学毕业证成绩单原件一模一样dyuozua
 
一比一原版(UofT毕业证书)多伦多大学毕业证成绩单原件一模一样
一比一原版(UofT毕业证书)多伦多大学毕业证成绩单原件一模一样一比一原版(UofT毕业证书)多伦多大学毕业证成绩单原件一模一样
一比一原版(UofT毕业证书)多伦多大学毕业证成绩单原件一模一样dyuozua
 
Premium Call Girls In Kapurthala} 9332606886❤️VVIP Sonya Call Girls
Premium Call Girls In Kapurthala} 9332606886❤️VVIP Sonya Call GirlsPremium Call Girls In Kapurthala} 9332606886❤️VVIP Sonya Call Girls
Premium Call Girls In Kapurthala} 9332606886❤️VVIP Sonya Call Girlsmeghakumariji156
 
一比一原版(UC毕业证书)坎特伯雷大学毕业证成绩单原件一模一样
一比一原版(UC毕业证书)坎特伯雷大学毕业证成绩单原件一模一样一比一原版(UC毕业证书)坎特伯雷大学毕业证成绩单原件一模一样
一比一原版(UC毕业证书)坎特伯雷大学毕业证成绩单原件一模一样dyuozua
 
一比一原版(UNITEC毕业证书)UNITEC理工学院毕业证成绩单原件一模一样
一比一原版(UNITEC毕业证书)UNITEC理工学院毕业证成绩单原件一模一样一比一原版(UNITEC毕业证书)UNITEC理工学院毕业证成绩单原件一模一样
一比一原版(UNITEC毕业证书)UNITEC理工学院毕业证成绩单原件一模一样dyuozua
 
一比一原版(Acadia毕业证书)加拿大阿卡迪亚大学毕业证学历认证可查认证
一比一原版(Acadia毕业证书)加拿大阿卡迪亚大学毕业证学历认证可查认证一比一原版(Acadia毕业证书)加拿大阿卡迪亚大学毕业证学历认证可查认证
一比一原版(Acadia毕业证书)加拿大阿卡迪亚大学毕业证学历认证可查认证xzxvi5zp
 
一比一原版(RUG毕业证书)格罗宁根大学毕业证成绩单原件一模一样
一比一原版(RUG毕业证书)格罗宁根大学毕业证成绩单原件一模一样一比一原版(RUG毕业证书)格罗宁根大学毕业证成绩单原件一模一样
一比一原版(RUG毕业证书)格罗宁根大学毕业证成绩单原件一模一样dyuozua
 

Recently uploaded (20)

一比一原版(UCD毕业证书)都柏林大学毕业证成绩单原件一模一样
一比一原版(UCD毕业证书)都柏林大学毕业证成绩单原件一模一样一比一原版(UCD毕业证书)都柏林大学毕业证成绩单原件一模一样
一比一原版(UCD毕业证书)都柏林大学毕业证成绩单原件一模一样
 
Dubai Call Girls/// Hot Afternoon O525547819 Call Girls In Dubai
Dubai Call Girls/// Hot Afternoon O525547819 Call Girls In DubaiDubai Call Girls/// Hot Afternoon O525547819 Call Girls In Dubai
Dubai Call Girls/// Hot Afternoon O525547819 Call Girls In Dubai
 
ITAU EQUITY_STRATEGY_WARM_UP_20240505 DHG.pdf
ITAU EQUITY_STRATEGY_WARM_UP_20240505 DHG.pdfITAU EQUITY_STRATEGY_WARM_UP_20240505 DHG.pdf
ITAU EQUITY_STRATEGY_WARM_UP_20240505 DHG.pdf
 
Camil Institutional Presentation_Mai24.pdf
Camil Institutional Presentation_Mai24.pdfCamil Institutional Presentation_Mai24.pdf
Camil Institutional Presentation_Mai24.pdf
 
一比一原版(UoA毕业证书)奥克兰大学毕业证成绩单原件一模一样
一比一原版(UoA毕业证书)奥克兰大学毕业证成绩单原件一模一样一比一原版(UoA毕业证书)奥克兰大学毕业证成绩单原件一模一样
一比一原版(UoA毕业证书)奥克兰大学毕业证成绩单原件一模一样
 
Gorakhpur Call Girls 8250092165 Low Price Escorts Service in Your Area
Gorakhpur Call Girls 8250092165 Low Price Escorts Service in Your AreaGorakhpur Call Girls 8250092165 Low Price Escorts Service in Your Area
Gorakhpur Call Girls 8250092165 Low Price Escorts Service in Your Area
 
一比一原版(EUR毕业证书)鹿特丹伊拉斯姆斯大学毕业证原件一模一样
一比一原版(EUR毕业证书)鹿特丹伊拉斯姆斯大学毕业证原件一模一样一比一原版(EUR毕业证书)鹿特丹伊拉斯姆斯大学毕业证原件一模一样
一比一原版(EUR毕业证书)鹿特丹伊拉斯姆斯大学毕业证原件一模一样
 
The Leonardo 1Q 2024 Results Presentation
The Leonardo 1Q 2024 Results PresentationThe Leonardo 1Q 2024 Results Presentation
The Leonardo 1Q 2024 Results Presentation
 
一比一原版(Waikato毕业证书)怀卡托大学毕业证成绩单原件一模一样
一比一原版(Waikato毕业证书)怀卡托大学毕业证成绩单原件一模一样一比一原版(Waikato毕业证书)怀卡托大学毕业证成绩单原件一模一样
一比一原版(Waikato毕业证书)怀卡托大学毕业证成绩单原件一模一样
 
一比一原版(AUT毕业证书)奥克兰理工大学毕业证成绩单原件一模一样
一比一原版(AUT毕业证书)奥克兰理工大学毕业证成绩单原件一模一样一比一原版(AUT毕业证书)奥克兰理工大学毕业证成绩单原件一模一样
一比一原版(AUT毕业证书)奥克兰理工大学毕业证成绩单原件一模一样
 
Western Copper and Gold - May 2024 Presentation
Western Copper and Gold - May 2024 PresentationWestern Copper and Gold - May 2024 Presentation
Western Copper and Gold - May 2024 Presentation
 
一比一原版(VUW毕业证书)惠灵顿维多利亚大学毕业证成绩单原件一模一样
一比一原版(VUW毕业证书)惠灵顿维多利亚大学毕业证成绩单原件一模一样一比一原版(VUW毕业证书)惠灵顿维多利亚大学毕业证成绩单原件一模一样
一比一原版(VUW毕业证书)惠灵顿维多利亚大学毕业证成绩单原件一模一样
 
一比一原版(MU毕业证书)梅努斯大学毕业证成绩单原件一模一样
一比一原版(MU毕业证书)梅努斯大学毕业证成绩单原件一模一样一比一原版(MU毕业证书)梅努斯大学毕业证成绩单原件一模一样
一比一原版(MU毕业证书)梅努斯大学毕业证成绩单原件一模一样
 
一比一原版(Galway毕业证书)爱尔兰高威大学毕业证成绩单原件一模一样
一比一原版(Galway毕业证书)爱尔兰高威大学毕业证成绩单原件一模一样一比一原版(Galway毕业证书)爱尔兰高威大学毕业证成绩单原件一模一样
一比一原版(Galway毕业证书)爱尔兰高威大学毕业证成绩单原件一模一样
 
一比一原版(UofT毕业证书)多伦多大学毕业证成绩单原件一模一样
一比一原版(UofT毕业证书)多伦多大学毕业证成绩单原件一模一样一比一原版(UofT毕业证书)多伦多大学毕业证成绩单原件一模一样
一比一原版(UofT毕业证书)多伦多大学毕业证成绩单原件一模一样
 
Premium Call Girls In Kapurthala} 9332606886❤️VVIP Sonya Call Girls
Premium Call Girls In Kapurthala} 9332606886❤️VVIP Sonya Call GirlsPremium Call Girls In Kapurthala} 9332606886❤️VVIP Sonya Call Girls
Premium Call Girls In Kapurthala} 9332606886❤️VVIP Sonya Call Girls
 
一比一原版(UC毕业证书)坎特伯雷大学毕业证成绩单原件一模一样
一比一原版(UC毕业证书)坎特伯雷大学毕业证成绩单原件一模一样一比一原版(UC毕业证书)坎特伯雷大学毕业证成绩单原件一模一样
一比一原版(UC毕业证书)坎特伯雷大学毕业证成绩单原件一模一样
 
一比一原版(UNITEC毕业证书)UNITEC理工学院毕业证成绩单原件一模一样
一比一原版(UNITEC毕业证书)UNITEC理工学院毕业证成绩单原件一模一样一比一原版(UNITEC毕业证书)UNITEC理工学院毕业证成绩单原件一模一样
一比一原版(UNITEC毕业证书)UNITEC理工学院毕业证成绩单原件一模一样
 
一比一原版(Acadia毕业证书)加拿大阿卡迪亚大学毕业证学历认证可查认证
一比一原版(Acadia毕业证书)加拿大阿卡迪亚大学毕业证学历认证可查认证一比一原版(Acadia毕业证书)加拿大阿卡迪亚大学毕业证学历认证可查认证
一比一原版(Acadia毕业证书)加拿大阿卡迪亚大学毕业证学历认证可查认证
 
一比一原版(RUG毕业证书)格罗宁根大学毕业证成绩单原件一模一样
一比一原版(RUG毕业证书)格罗宁根大学毕业证成绩单原件一模一样一比一原版(RUG毕业证书)格罗宁根大学毕业证成绩单原件一模一样
一比一原版(RUG毕业证书)格罗宁根大学毕业证成绩单原件一模一样
 

Pandas cheat sheet_data science

  • 1. F M A Data Wrangling with pandas Cheat Sheet http://pandas.pydata.org Syntax – Creating DataFrames Tidy Data – A foundation for wrangling in pandas In a tidy data set: F M A Each variable is saved in its own column &Each observation is saved in its own row Tidy data complements pandas’s vectorized operations. pandas will automatically preserve observations as you manipulate variables. No other format works as intuitively with pandas. Reshaping Data – Change the layout of a data set M A F * M A* pd.melt(df) Gather columns into rows. df.pivot(columns='var', values='val') Spread rows into columns. pd.concat([df1,df2]) Append rows of DataFrames pd.concat([df1,df2], axis=1) Append columns of DataFrames df.sort_values('mpg') Order rows by values of a column (low to high). df.sort_values('mpg',ascending=False) Order rows by values of a column (high to low). df.rename(columns = {'y':'year'}) Rename the columns of a DataFrame df.sort_index() Sort the index of a DataFrame df.reset_index() Reset index of DataFrame to row numbers, moving index to columns. df.drop(columns=['Length','Height']) Drop columns from DataFrame Subset Observations (Rows) Subset Variables (Columns) a b c 1 4 7 10 2 5 8 11 3 6 9 12 df = pd.DataFrame( {"a" : [4 ,5, 6], "b" : [7, 8, 9], "c" : [10, 11, 12]}, index = [1, 2, 3]) Specify values for each column. df = pd.DataFrame( [[4, 7, 10], [5, 8, 11], [6, 9, 12]], index=[1, 2, 3], columns=['a', 'b', 'c']) Specify values for each row. a b c n v d 1 4 7 10 2 5 8 11 e 2 6 9 12 df = pd.DataFrame( {"a" : [4 ,5, 6], "b" : [7, 8, 9], "c" : [10, 11, 12]}, index = pd.MultiIndex.from_tuples( [('d',1),('d',2),('e',2)], names=['n','v'])) Create DataFrame with a MultiIndex Method Chaining Most pandas methods return a DataFrame so that another pandas method can be applied to the result. This improves readability of code. df = (pd.melt(df) .rename(columns={ 'variable' : 'var', 'value' : 'val'}) .query('val >= 200') ) df[df.Length > 7] Extract rows that meet logical criteria. df.drop_duplicates() Remove duplicate rows (only considers columns). df.head(n) Select first n rows. df.tail(n) Select last n rows. Logic in Python (and pandas) < Less than != Not equal to > Greater than df.column.isin(values) Group membership == Equals pd.isnull(obj) Is NaN <= Less than or equals pd.notnull(obj) Is not NaN >= Greater than or equals &,|,~,^,df.any(),df.all() Logical and, or, not, xor, any, all http://pandas.pydata.org/ This cheat sheet inspired by Rstudio Data Wrangling Cheatsheet (https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf) Written by Irv Lustig, Princeton Consultants df[['width','length','species']] Select multiple columns with specific names. df['width'] or df.width Select single column with specific name. df.filter(regex='regex') Select columns whose name matches regular expression regex. df.loc[:,'x2':'x4'] Select all columns between x2 and x4 (inclusive). df.iloc[:,[1,2,5]] Select columns in positions 1, 2 and 5 (first column is 0). df.loc[df['a'] > 10, ['a','c']] Select rows meeting logical condition, and only the specific columns . regex (Regular Expressions) Examples '.' Matches strings containing a period '.' 'Length$' Matches strings ending with word 'Length' '^Sepal' Matches strings beginning with the word 'Sepal' '^x[1-5]$' Matches strings beginning with 'x' and ending with 1,2,3,4,5 '^(?!Species$).*' Matches strings except the string 'Species' df.sample(frac=0.5) Randomly select fraction of rows. df.sample(n=10) Randomly select n rows. df.iloc[10:20] Select rows by position. df.nlargest(n, 'value') Select and order top n entries. df.nsmallest(n, 'value') Select and order bottom n entries.
  • 2. Summarize Data Make New Columns Combine Data Sets df['w'].value_counts() Count number of rows with each unique value of variable len(df) # of rows in DataFrame. df['w'].nunique() # of distinct values in a column. df.describe() Basic descriptive statistics for each column (or GroupBy) pandas provides a large set of summary functions that operate on different kinds of pandas objects (DataFrame columns, Series, GroupBy, Expanding and Rolling (see below)) and produce single values for each of the groups. When applied to a DataFrame, the result is returned as a pandas Series for each column. Examples: sum() Sum values of each object. count() Count non-NA/null values of each object. median() Median value of each object. quantile([0.25,0.75]) Quantiles of each object. apply(function) Apply function to each object. min() Minimum value in each object. max() Maximum value in each object. mean() Mean value of each object. var() Variance of each object. std() Standard deviation of each object. df.assign(Area=lambda df: df.Length*df.Height) Compute and append one or more new columns. df['Volume'] = df.Length*df.Height*df.Depth Add single column. pd.qcut(df.col, n, labels=False) Bin column into n buckets. Vector function Vector function pandas provides a large set of vector functions that operate on all columns of a DataFrame or a single selected column (a pandas Series). These functions produce vectors of values for each of the columns, or a single Series for the individual Series. Examples: shift(1) Copy with values shifted by 1. rank(method='dense') Ranks with no gaps. rank(method='min') Ranks. Ties get min rank. rank(pct=True) Ranks rescaled to interval [0, 1]. rank(method='first') Ranks. Ties go to first value. shift(-1) Copy with values lagged by 1. cumsum() Cumulative sum. cummax() Cumulative max. cummin() Cumulative min. cumprod() Cumulative product. x1 x2 A 1 B 2 C 3 x1 x3 A T B F D T adf bdf Standard Joins x1 x2 x3 A 1 T B 2 F C 3 NaN x1 x2 x3 A 1.0 T B 2.0 F D NaN T x1 x2 x3 A 1 T B 2 F x1 x2 x3 A 1 T B 2 F C 3 NaN D NaN T pd.merge(adf, bdf, how='left', on='x1') Join matching rows from bdf to adf. pd.merge(adf, bdf, how='right', on='x1') Join matching rows from adf to bdf. pd.merge(adf, bdf, how='inner', on='x1') Join data. Retain only rows in both sets. pd.merge(adf, bdf, how='outer', on='x1') Join data. Retain all values, all rows. Filtering Joins x1 x2 A 1 B 2 x1 x2 C 3 adf[adf.x1.isin(bdf.x1)] All rows in adf that have a match in bdf. adf[~adf.x1.isin(bdf.x1)] All rows in adf that do not have a match in bdf. x1 x2 A 1 B 2 C 3 x1 x2 B 2 C 3 D 4 ydf zdf Set-like Operations x1 x2 B 2 C 3 x1 x2 A 1 B 2 C 3 D 4 x1 x2 A 1 pd.merge(ydf, zdf) Rows that appear in both ydf and zdf (Intersection). pd.merge(ydf, zdf, how='outer') Rows that appear in either or both ydf and zdf (Union). pd.merge(ydf, zdf, how='outer', indicator=True) .query('_merge == "left_only"') .drop(columns=['_merge']) Rows that appear in ydf but not zdf (Setdiff). Group Data df.groupby(by="col") Return a GroupBy object, grouped by values in column named "col". df.groupby(level="ind") Return a GroupBy object, grouped by values in index level named "ind". All of the summary functions listed above can be applied to a group. Additional GroupBy functions: max(axis=1) Element-wise max. clip(lower=-10,upper=10) Trim values at input thresholds min(axis=1) Element-wise min. abs() Absolute value. The examples below can also be applied to groups. In this case, the function is applied on a per-group basis, and the returned vectors are of the length of the original DataFrame. Windows df.expanding() Return an Expanding object allowing summary functions to be applied cumulatively. df.rolling(n) Return a Rolling object allowing summary functions to be applied to windows of length n. size() Size of each group. agg(function) Aggregate group using function. Handling Missing Data df.dropna() Drop rows with any column having NA/null data. df.fillna(value) Replace all NA/null data with value. Plotting df.plot.hist() Histogram for each column df.plot.scatter(x='w',y='h') Scatter chart using pairs of points http://pandas.pydata.org/ This cheat sheet inspired by Rstudio Data Wrangling Cheatsheet (https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf) Written by Irv Lustig, Princeton Consultants