Python For Data Science
Python For Data Science
Data Science
Introduction to Data Science
Overview of Python Libraries for Data
Tutorial Content Scientists
Descriptive statistics
Inferential statistics
2
Python Libraries for Data Science
Many popular Python toolboxes/libraries:
• NumPy
• SciPy
• Pandas
• SciKit-Learn
Visualization libraries
• matplotlib
• Seaborn
3
Python Libraries for Data Science
NumPy:
▪ introduces objects for multidimensional arrays and matrices, as well as
functions that allow to easily perform advanced mathematical and statistical
operations on those objects
Link: http://www.numpy.org/
4
Python Libraries for Data Science
SciPy:
▪ collection of algorithms for linear algebra, differential equations, numerical
integration, optimization, statistics and more
▪ built on NumPy
Link: https://www.scipy.org/scipylib/
5
Python Libraries for Data Science
Pandas:
▪ adds data structures and tools designed to work with table-like data (similar
to Series and Data Frames in R)
Link: http://pandas.pydata.org/
6
Python Libraries for Data Science
SciKit-Learn:
▪ provides machine learning algorithms: classification, regression, clustering,
model validation etc.
Link: http://scikit-learn.org/
7
Python Libraries for Data Science
matplotlib:
▪ python 2D plotting library which produces publication quality figures in a
variety of hard copy formats
Link: https://matplotlib.org/
8
Python Libraries for Data Science
Seaborn:
▪ based on matplotlib
Link: https://seaborn.pydata.org/
9
Download Tutorial NoteBook
# The notebook file “dataScience.ipynb” is uploaded on google classroom you can get it from there.
10
Start Jupyter NoteBook
11
Loading Python Libraries
In [ ]: #Import Python Libraries
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib as mpl
import seaborn as sns
12
Reading Data Using Pandas
In [ ]: #Read csv file
df = pd.read_csv("Salaries.csv")
Note: The above command has many optional arguments to fine-tune the data import process.
pd.read_excel('myfile.xlsx',sheet_name='Sheet1', index_col=None,
na_values=['NA'])
pd.read_stata('myfile.dta')
pd.read_sas('myfile.sas7bdat')
pd.read_hdf('myfile.h5','df')
13
Exploring Data Frames
In [3]: #List first 5 records
df.head()
Out[3]:
14
Hands-on exercises
✓ Try to read the first 10, 20, 50 records;
✓ Can you guess how to view the last few records; Hint:
15
Data Frames : Data Types
Pandas Type Native Python Type Description
object string The most general dtype. Will be
assigned to your column if
column has mixed types
(numbers and strings).
int64 int Numeric characters. 64 refers to
the memory allocated to hold
this character.
float64 float Numeric characters with
decimals. If a column contains
numbers and NaNs(see below),
pandas will default to float64, in
case your missing value has a
decimal.
datetime64, timedelta[ns] N/A (but see Values meant to hold time data.
the datetime module in Python’s Look into these for time series
standard library) experiments.
16
Data Frames : Data Types
In [4]: #Check a particular column type
df['salary'].dtype
Out[4]: dtype('int64')
df.attribute description
dtypes list the types of the columns
columns list the column names
axes list the row labels and column names
ndim number of dimensions
18
Hands-on exercises
✓ Find how many records this data frame has;
19
Data Frames : Methods
Unlike attributes, python methods have parenthesis.
All attributes and methods can be listed with a dir() function: dir(df)
df.method() description
head( [n] ), tail( [n] ) first/last n rows
✓ What are the mean values of the first 50 records in the dataset? Hint: use
head() method to subset the first 50 records and then calculate the mean
21
Selecting a Column in a Data Frame
Method 1: Subset the data frame using column name:
df['sex']
Note: there is an attribute rank for pandas data frames, so to select a column with a name
"rank" we should use method 1.
22
Hands-on exercises
✓ Calculate the basic statistics for the salary column;
✓ Find how many values in the salary column (use count method);
23
Data Frames groupby Method
Using "group by" method we can:
In [ ]: #Calculate mean value for each numeric column per each group
df_rank.mean()
24
Data Frames groupby Method
Once groupby object is create we can calculate various statistics for each group:
Note: If single brackets are used to specify the column (e.g. salary), then the output is Pandas Series object.
When double brackets are used the output is a Data Frame
25
Data Frames groupby Method
groupby performance notes:
26
Data Frames : Filtering
To subset the data we can apply Boolean indexing. This indexing is commonly
known as a filter. For example if we want to subset the rows in which the salary
value is greater than $120K:
28
Data Frames : Slicing
When selecting one column, it is possible to use single set of brackets, but the
resulting object will be a Series (not a DataFrame):
In [ ]: #Select column salary:
df['salary']
When we need to select more than one column and/or make the output to be a
DataFrame, we should use double brackets:
In [ ]: #Select column salary:
df[['rank','salary']]
29
Data Frames : Selecting Rows
If we need to select a range of rows, we can specify the range using ":"
Notice that the first row has a position 0, and the last value in the range is
omitted:
So for 0:10 range the first 10 rows are returned with the positions starting with 0
and ending with 9
30
Data Frames : Method (loc)
If we need to select a range of rows, using their labels we can use method loc:
Out[ ]:
31
Data Frames : Method(iloc)
If we need to select a range of rows and/or columns, using their positions we can
use method iloc:
In [ ]: #Select rows by their labels:
df_sub.iloc[10:20,[0, 3, 4, 5]]
Out[ ]:
32
Data Frames: Method(iloc) - Summary
df.iloc[0] # First row of a data frame
df.iloc[i] #(i+1)th row
df.iloc[-1] # Last row
33
Data Frames : Sorting
We can sort the data by a value in the column. By default the sorting will occur in
ascending order and a new data frame is return.
In [ ]: # Create a new data frame from the original sorted by the column Salary
df_sorted = df.sort_values( by ='service')
df_sorted.head()
Out[ ]:
34
Data Frames : Sorting
We can sort the data using 2 or more columns:
In [ ]: df_sorted = df.sort_values( by =['service', 'salary'], ascending = [True, False])
df_sorted.head(10)
Out[ ]:
35
Missing Values
Missing values are marked as NaN
In [ ]: # Read a dataset with missing values
flights = pd.read_csv("flights.csv")
Out[ ]:
36
Missing Values
There are a number of methods to deal with missing values in the data frame:
df.method() description
dropna() Drop missing observations
38
Aggregation Functions in Pandas
Aggregation - computing a summary statistic about each group, i.e.
• compute group sums or means
• compute group sizes/counts
min, max
count, sum, prod
mean, median, mode, mad
std, var
39
Aggregation Functions in Pandas
agg() method are useful when multiple statistics are computed per column:
In [ ]: flights[['dep_delay','arr_delay']].agg(['min','mean','max'])
Out[ ]:
40
Basic Descriptive Statistics
df.method() description
describe Basic statistics (count, mean, std, min, quantiles, max)
kurt kurtosis
41
Graphics to Explore the Data
Seaborn package is built on matplotlib but provides high level
interface for drawing attractive statistical graphics, similar to ggplot2
library in R. It specifically targets statistical data visualization
In [ ]: %matplotlib inline
42
Graphics
description
distplot histogram
barplot estimate of central tendency for a numeric variable
violinplot similar to boxplot, also shows the probability density of the
data
jointplot Scatterplot
regplot Regression plot
pairplot Pairplot
boxplot boxplot
swarmplot categorical scatterplot
factorplot General categorical plot
43
Basic Statistical Analysis
statsmodel and scikit-learn - both have a number of function for statistical analysis
The first one is mostly used for regular analysis using R style formulas, while scikit-learn is
more tailored for Machine Learning.
statsmodels:
• linear regressions
• ANOVA tests
• hypothesis testings
• many more ...
scikit-learn:
• kmeans
• support vector machines
• random forests
• many more ...
Questions:
email: umairmajeed61@gmail.com (Umair Majeed)
email: msds17005@itu.edu.pk (Faizan Saeed)
45