Python Data Analysis Techniques
Python Data Analysis Techniques
with Python
Importing Datasets
Python Packages for Data Science
Scientific Computing Visualization Algorithmic
Libraries Libraries Libraries
Folder API
Importing Data
Two important factors:
import pandas as pd
url = “[Link]
df = pd.read_csv(url)
Printing Data in Python
df returns (prints out) the
entire dataset (DataFrame)
[Link](n) returns
(prints out) the first n rows
of a DataFrame
[Link](n) returns
(prints out) the last n rows
of a DataFrame
Exporting Data to CSV
Save modified or processed dataset
path = “C:/Windows/User/Downloads/[Link]”
df.to_csv(path)
Exporting to Different Formats in Python
Should check:
Data Types
Data Distribution
Locate potential issues with the data
Basic Insight of Dataset – Data Type
[Link]
Basic Insight of Dataset – Data Distribution
In Pandas, [Link] returns a statistical summary
[Link]()
Basic Insight of Dataset – Data Distribution
[Link](include=“all”)
[Link](include=“all”)
returns summary statistics
Data Wrangling
Data Preprocessing
The process of transforming raw data into a format that is suitable
and effective for further analysis (machine learning algorithm,
statistical analysis, visualization)
Data Preprocessing Steps
Identify and handle missing values
Data formatting
Data normalization
Data binning
df = [Link](subset=[“price”], axis=0)
How To Replace Missing Values
Use [Link](missing_value, new_value)
mean = df[“age”].mean()
[Link]([Link], mean)
Data Formatting
Bringing data into a common standard expression
City City
Non-formatted NY New York Formatted
New York New York
N.Y New York
N.Y New York
Data Formatting
Correct data types using [Link]()
df[“price”] = df[“price”].astype(“int”)
Data Normalization
age income
age income
scale [20,45] [20000,500000]
20 100000
impact small large
30 20000
40 500000
45 150000
age and income are in different ranges
𝑥𝑜𝑙𝑑 − 𝑥𝑚𝑖𝑛
Min-Max 𝑥𝑛𝑒𝑤 =
𝑥𝑚𝑎𝑥 − 𝑥𝑚𝑖𝑛
𝑥𝑜𝑙𝑑 − 𝜇
Z-Score 𝑥𝑛𝑒𝑤 =
𝜎
Simple Feature Scaling
df[“length”] = (df[“length”]–df[“length”].mean())/df[“length”].std()
Binning
Grouping of values into “bins”
car fuel
A gas
B diesel
C gas
D gas
Categorical -> Numeric
Add dummy variables for each unique categories
Assign 0 or 1 in each category
car fuel gas diesel
A gas 1 0
B diesel 0 1
C gas 1 0
D gas 1 0
One-hot encoding
Dummy Variable in Python
Use pandas.get_dummies() method to convert categorical
variables to dummy variables (0 or 1)
fuel gas diesel
gas 1 0
diesel 0 1
gas 1 0
gas 1 0
pd.get_dummies(df[“fuel”])
Exploratory Data Analysis
Exploratory Data Analysis (EDA)
Preliminary step in data analysis to:
Summarize main features of the data
Gain better understanding of the dataset
Uncover relationships between features
Extract important features
Exploratory Data Analysis (EDA)
Typically involves the following steps:
Descriptive statistics
Grouping data using GroupBy
Correlation
Descriptive Statistics
Describe basic features of the sample data and give short
summaries about it
Generate summary statistics
[Link]()
Descriptive Stats–Categorical Variable Distribution
Summarize categorical variables by using value_counts()
method
df[‘age-bracket’].describe()
Descriptive Stats–Data Distribution with Boxplots
100
90 Upper Extreme
80 Whisker
Upper Quartile
70
60
50 Median
40
30 Lower Quartile
20
10 Lower Extreme
Outlier/Data point
0
Descriptive Stats–Data Distribution with Boxplots
Generate boxplot of sample data using seaborn’s boxplot()
method
[Link](
x='smoker’,
y=‘bmi’,
data=df
)
Descriptive Stats – Relationships with Scatterplot
[Link](
df['engine-size’],
df['price’]
)
Grouping Data
Use pandas [Link]() method to group categorical variables
into distinct groups/categories
GroupBy with One Categorical Variable
[Link]('sex')['bmi'].mean()
GroupBy with Multiple Categorical Variables
[Link](['sex', 'smoker'])['bmi'].mean()
Grouping Data - Pandas pivot_table Method
Use pandas df.pivot_table() method to create pivot tables
One can choose what variables to display along the columns and
rows of the pivot table
df.pivot_table(
index='sex’,
columns='smoker’,
values='bmi’
)
Correlation
Measures to what extent different numeric variables are
interdependent
Sales Profit
Correlation
[Link](x='engine-size', y='price', data=df)
p-value
p-value < 0.001: strong certainty in the result
p-value < 0.05: moderate certainty in the result
p-value < 0.1: weak certainty in the result
p-value > 0.1: no certainty in the result
Pearson Correlation - Example
coef, p_value = [Link](
autos['horsepower’],
autos['price’]
)
contingency_table = [Link](
autos['fuel-type’],
autos['aspiration’]
)
Association
[Link].chi2_contingency(contingency_table,
correction = True)
Conclusion
Chi-square test value is 30.03
The p-value is 4.24e-08 (4.24 * 10-8) (very close to zero)
Since p-value is close to zero, we reject the null hypothesis that the two variables are
independent and conclude that there is evidence of association between the two variables
Model Development
Model Development
A model is a mathematical equation used to predict a value, given
one or more other values.
Relates one or more independent variables to one dependent
variable.
Value(s) of the independent variable(s) are a given to the model and
used by the model to predict a value for the dependent variable.
engine size This car is
$3000
make
mileage
horsepower
Independent variables Dependent variable or
or features target variable
Model
‘highway-mpg’ ‘price’
55 mpg $5000
prediction
Usually, the more relevant data you have the more accurate your
model is
‘horsepower’
Model
‘engine-size’ ‘price’
‘drive-wheels’
$5400
‘highway-mpg’
Linear Regression
Simple linear regression
Independent
will refer to one variable Simple Linear prediction
independent variable to 𝑥1
Regression
𝑦
make a prediction
𝑦 = 𝑏0 + 𝑏1 𝑥
b0 : the intercept
b1 : the slope or coefficient
Simple Linear Regression - Fit
After ascertaining that there is a linear relationship between the
two variables, what we do next is to determine the
line/equation/model that best represents the relationship.
The process of doing so is called fitting.
Hence, we try to find the line of best fit.
‘price’
Preprocessed data ‘highway-mpg’
𝑦 = 𝑏0 + 𝑏1 𝑥
(b0 , b1)
𝑦 = 38423 − 821𝑥
Simple Linear Regression – Prediction
b0 : 38423
b1 : -821
𝑦 = 38423 − 821𝑥
𝑦 = 38423 − 821𝑥
𝑦 = 38423 − 821(20)
𝑦ො = 22003
predictions = y_hat = 𝒚
ෝ
Fitting a Simple Linear Model Estimator
from sklearn.linear_model import LinearRegression
model = LinearRegression()
X = df[[‘highway-mpg’]]
y = df[‘price’]
[Link](X, y)
y_hat = [Link](X)
Estimated Linear Model
model.intercept_ b0
38423.31
model.coef_
b1
-821.73
𝑦 = 𝑏0 + 𝑏1 𝑥1 + 𝑏2 𝑥2+ 𝑏3 𝑥3
model = LinearRegression()
y = df[‘price’]
[Link](X, y)
y_hat = [Link](X)
Model Evaluation using Visualization
Regression plot
Residual plot
Distribution plot
Regression Plot
Regression plot shows a combination of:
A scatterplot
The fitted linear regression line
Regression Plot
import seaborn as sns
[Link](x='highway-mpg', y='price', data=df)
Residual Plot
Residuals are the differences between actual values of y and
predicted values of y
ෝ
𝒚−𝒚
We then plot the values of the independent variable against the
residuals to obtain a residual plot
Residual Plot
import seaborn as sns
[Link](x='highway-mpg', y='price', data=df)
Distribution Plot
Distribution plot shows a comparison of:
The distribution of actual values of y
The distribution of predicted values of y
Distribution Plot
ax1 = [Link](
autos['price’],
hist=False,
color=‘r’,
label='Actual Value’
)
[Link](yhat,
hist=False,
color='b’,
label='Predicted Values’,
ax=ax1
)
error = residuals = actual values – predicted values = y - ŷ
Polynomial Regression
A special case of general linear regression
2 2
𝑦ො = 𝑏0 + 𝑏1 𝑥1 + 𝑏2 𝑥2 + 𝑏3 𝑥1 𝑥2 + 𝑏4 𝑥1 + 𝑏5 𝑥2
Polynomial Regression
from [Link] import PolynomialFeatures
pr = PolynomialFeatures(degrees=2, include_bias=False)
x_pr = pr.fit_transform(
df[[‘highway-mpg’, ‘horsepower’]]
)
ෝ = 𝒃𝟎 + 𝒃𝟏 𝒙𝟏 + 𝒃𝟐 𝒙𝟐 + 𝒃𝟑 𝒙𝟏 𝒙𝟐 + 𝒃𝟒 𝒙𝟏 𝟐 𝟐
𝒚 + 𝒃𝟓 𝒙𝟐
Methods for Data Normalization
𝑥𝑜𝑙𝑑
Simple Feature Scaling 𝑥𝑛𝑒𝑤 =
𝑥𝑚𝑎𝑥
𝑥𝑜𝑙𝑑 − 𝑥𝑚𝑖𝑛
Min-Max 𝑥𝑛𝑒𝑤 =
𝑥𝑚𝑎𝑥 − 𝑥𝑚𝑖𝑛
𝑥𝑜𝑙𝑑 − 𝜇
Z-Score 𝑥𝑛𝑒𝑤 =
𝜎
Preprocessing – Data Normalization
We can normalize multiple features simultaneously:
scaler = StandardScaler()
X_scaled = scaler.fit_transform(
df[[‘highway-mpg’, ‘horsepower’]]
)
Polynomial
Normalization Regression
Transformation
Polynomial
Normalization Regression
Transformation
Pipelines
y_hat = [Link](df[[‘highway-mpg’, ‘horsepower’]])
Measures for In-Sample Evaluation
A way to numerically determine how good a model fits a dataset
mean_squared_error(df[‘price’], y_hat)
3163502.9446
R-Squared (R2)
Also referred to as Coefficient of Determination
10000+3600+100+100 625+25+1225+225
= =
4 4
= 3450 = 525
R-Squared (R2)
3450
𝑅 =1-
2
525
𝑅 = 1 - 6.57
2
R-Squared (R2)
Generally values of R-Squared are between 0 and 1
A value near 1 means that the line is a good fit for the data
A value near 0 means that the line is not a good fit for the data
y = df[‘price’]
[Link](X, y)
[Link](X, y)
0.496591188
Model Evaluation
Model Evaluation
There two types of model evaluation:
In-sample evaluation
Out-of-sample evaluation
In-sample evaluation Out-of-sample evaluation
…being observed
taking 100 shots.
Scenario 1: Using a Lot of Training Data (90% Training, 10% Testing)
You watch the player take 100 shots (90 for training, 10 for testing)
First try: They make 8/10 test shots → 80% accuracy
Second try: They make 7/10 → 70% accuracy
Third try: They make 9/10 → 90% accuracy
What’s happening?
Each test is close to their true generalization error, but the results vary a lot
(low precision)
This is because the test set is small (only 10 shots), so luck plays a big role
70 80 90
You watch the player take 100 shots (10 for training, 90 for testing)
First try: They make 72/90 → 80% accuracy
Second try: They make 75/90 → 83% accuracy
Third try: They make 70/90 → 78% accuracy
What’s happening?
The results are more consistent (higher precision) because the test set is
larger
But you had to use less training data (only 10 shots), so your model might
not learn as well
78 80 83
70 80 90 78 80 83
More Training Data → High Accuracy More Testing Data → High Precision
(Low Bias in Model) (Low Variance in Estimates)
Less Testing Data → High Precision Less Training Data → Low Accuracy
(High Variance in Estimates) (High Bias in Model)
True Generalization
Error
Scenario 1 Scenario 2
70 80 90 78 80 83
Scenario 1 Scenario 2
Test
1st time
1st fold 2nd fold 3rd fold 4th fold
2nd time
3rd time
4th time
𝑀𝑆𝐸 𝑜𝑓 𝑟𝑒𝑔𝑟𝑒𝑠𝑠𝑖𝑜𝑛 𝑙𝑖𝑛𝑒
𝑅2 = 1 -
𝑀𝑆𝐸 𝑜𝑓 𝑚𝑒𝑎𝑛 𝑜𝑓 𝑦
Model
cross_val_score() Function
from sklearn.model_selection import cross_val_score
[Link](scores)
Overfitting and Underfitting
Overfitting is where the model is too flexible and fits the noise
rather than the function
Underfitting is where the model is too simple to fit the data
Overfitting and Underfitting
Underfitting Overfitting
Alpha x x2 x3 x4 x5 x6 x7 x8 x9 x10
model = Ridge(alpha=0.1)
[Link](X, y)
y_hat = [Link](X)
Ridge Regression
Data:
Ridge Regression
Data:
This is similar to test data, but it is used to select parameters like alpha
Ridge Regression
Alpha R2
0.1 Model 1 Model 1 0.5
Train Evaluate
Train Evaluate
Train Evaluate
Hyperparameters
Because we are manually setting different values for alpha just to
select the best alpha value which maximizes the R2, we call alpha a
hyperparameter.
Hyperparameters are the "knobs" or "settings" you manually tune
before training a machine learning model. They control how the
model learns from data.
Hyperparameters are not estimated from the data but are instead
chosen by the practitioner or optimized via external methods
Grid Search
Scikit-learn has a means of automatically iterating over these
hyperparameters using cross-validation called Grid Search.
Grid Search
Ridge
Scoring
Method
(R2, MSE)
Alpha 1 10 100 1000
Grid Search CV R2 0.74 0.35 0.073 0.008
Number
of folds