0% found this document useful (0 votes)
4 views9 pages

Python Practicals Study Guide

This document is a line-by-line study guide for Python data science practicals, focusing on data cleaning, correlation analysis, and visualization using libraries like Seaborn and Pandas. It provides detailed explanations of code snippets, memory tricks, and practical steps for working with datasets such as the Iris and Titanic datasets. The guide emphasizes understanding the purpose of each code line and includes a quick reference cheat sheet for essential functions.

Uploaded by

denztenz37
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

Python Practicals Study Guide

This document is a line-by-line study guide for Python data science practicals, focusing on data cleaning, correlation analysis, and visualization using libraries like Seaborn and Pandas. It provides detailed explanations of code snippets, memory tricks, and practical steps for working with datasets such as the Iris and Titanic datasets. The guide emphasizes understanding the purpose of each code line and includes a quick reference cheat sheet for essential functions.

Uploaded by

denztenz37
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

🐍 Python Data Science

Practicals — Line-by-Line Study Guide


Practicals 1 • 2 • 3 | Easy Learn & Memorize Edition

📚 How to Use This Guide


This document breaks every line of code into simple English. Use the following method to memorize
fast:

• Read the CODE column — understand what it says.


• Read the EXPLANATION column — understand WHY it is written.
• Cover the code and try to rewrite it from memory.
• Focus on the MEMORY TRICK boxes — they give you shortcuts to recall code quickly.

📊 Practical 1
Data Cleaning & Correlation Analysis using Seaborn

Practical 1 — Data Cleaning & Correlation


Goal: Load a dataset, find missing values, remove duplicates, detect outliers using IQR method, and
compute correlations between numeric columns.

Step 1 — Import Libraries


💻 Code 📖 What it does / Why it's used
import seaborn as sns Imports Seaborn (data visualization library). 'as sns' means
you can type sns instead of seaborn — shorter!
import pandas as pd Imports Pandas (data table/spreadsheet library). 'as pd' is
💻 Code 📖 What it does / Why it's used
the standard short name.
import [Link] as Imports Matplotlib's plotting module. All charts are shown
plt using this.
import numpy as np Imports NumPy (math and array library). Used for
percentile calculations.

🧠 Memory Trick — Import Order


Always remember: S-P-M-N = Seaborn, Pandas, Matplotlib, NumPy. Think: 'Some People
Make Numbers'

Step 2 — Load & Inspect Data


💻 Code 📖 What it does / Why it's used
df = pd.read_csv('[Link]') Reads the CSV file named '[Link]' from your folder and
stores it in a variable called df (DataFrame = a table).
print(df) Displays the full table in the console.
dfnomis = [Link]() Counts non-null (non-missing) values in each column.
Stores result in dfnomis.
dftotal = [Link][0] Gets total number of rows. shape gives (rows, columns), so
shape[0] = rows.
df_mis = dftotal - dfnomis Subtracts non-missing count from total rows = gives you
missing values per column.
print("Missing values...\n", Prints the missing value count for each column with a label.
df_mis)

🧠 Memory Trick — Missing Values Formula


Missing = Total Rows - Non-Null Count → df_mis = dftotal - dfnomis

Step 3 — Clean Data (Duplicates & Nulls)


💻 Code 📖 What it does / Why it's used
df1 = df.drop_duplicates() Removes duplicate rows (rows that are exactly the same).
Result stored in df1.
df1 = [Link]() Removes rows that have any missing (NaN) value. Keeps
only complete rows.
print(df1) Shows the cleaned table.
💡 Why clean data?
Machine learning and statistics only work correctly on clean, complete data. Dirty data =
wrong results.

Step 4 — Outlier Detection using IQR Method


IQR = Inter-Quartile Range. It measures the 'middle spread' of data. Values too far outside this range
are called outliers.

💻 Code 📖 What it does / Why it's used


Q1 = [Link](df1['sal'], Gets the 25th percentile (Q1) of the 'sal' column — the
25) value below which 25% of data falls.
Q3 = [Link](df1['sal'], Gets the 75th percentile (Q3) — the value below which
75) 75% of data falls.
IQR = Q3 - Q1 Calculates the Inter-Quartile Range = spread of the middle
50% of data.
ul = Q3 + 1.5 * IQR Upper Limit: anything above this is an outlier (too high).
ll = Q1 - 1.5 * IQR Lower Limit: anything below this is an outlier (too low).
df1_non_outliers = Filters the DataFrame — keeps only rows where salary is
df1[(df1['sal'] >= ll) & within the limits (no outliers).
(df1['sal'] <= ul)]
print("Length with outliers:", Shows how many rows existed before removing outliers.
len(df1))
print("Length without Shows how many rows remain after removing outliers.
outliers:",
len(df1_non_outliers))

🧠 IQR Formula to Memorize


Lower Limit = Q1 - 1.5×IQR | Upper Limit = Q3 + 1.5×IQR Think: 'Stretch 1.5 times the
middle range on both sides.'

Step 5 — Correlation Analysis


💻 Code 📖 What it does / Why it's used
print(df['exper'].corr(df['sal Pearson: measures linear relationship between experience
'], method='pearson')) & salary. Value between -1 and 1.
print(df['exper'].corr(df['sal Spearman: rank-based correlation. Good when data is not
'], method='spearman')) normally distributed.
print(df['exper'].corr(df['sal Kendall: another rank-based method. More robust with
'], method='kendall')) small samples or many ties.
df_corr = Creates a full correlation matrix for all numeric columns in
💻 Code 📖 What it does / Why it's used
[Link](numeric_only=True) the dataset.
print(df_corr) Prints the correlation matrix table.
print(df['sal'].median()) Shows the median salary value (middle value when
sorted).
print([Link]()) Prints summary statistics: count, mean, std, min, max, Q1,
Q3 for all numeric columns.

🧠 3 Correlation Methods — Quick Recall


P-S-K = Pearson (linear), Spearman (rank), Kendall (robust rank) Think: 'Please Send
Knowledge'

Step 6 — Heatmap Visualization


💻 Code 📖 What it does / Why it's used
[Link](df_corr, vmin=-1, Draws a colored grid (heatmap) of the correlation matrix.
vmax=1, annot=True) annot=True shows numbers inside each cell. vmin/vmax
set the color scale from -1 to 1.
[Link]() Displays the chart on screen.

💡 Why use a Heatmap?


A heatmap makes it easy to spot strong correlations (dark red/blue) vs weak ones (light
colors) at a glance.

🌸 Practical 2
Iris Dataset — Exploration & Inspection

Practical 2 — Iris Dataset Exploration


Goal: Load the famous Iris dataset, inspect its shape, data types, missing values, and basic statistics.

Step 1 — Import Libraries


Same imports as Practical 1: seaborn, pandas, matplotlib, numpy. No new imports needed.
Step 2 — Load & Basic Info
💻 Code 📖 What it does / Why it's used
df = pd.read_csv('[Link]') Loads the [Link] file into a DataFrame called df.
print(df) Prints the entire dataset.
print([Link]) Prints total number of elements = rows × columns.
print("Rows = ", [Link][0]) Prints only the number of rows.
print("Cols = ", [Link][1]) Prints only the number of columns.
print([Link]) Prints (rows, columns) together as a tuple.
print([Link]) Prints the raw data as a NumPy array (no column
headers).

🧠 shape vs size
shape = (rows, cols) → structure | size = rows × cols → total cells Think: Shape =
skeleton, Size = total bricks.

Step 3 — Tail, Head & Summary


💻 Code 📖 What it does / Why it's used
print([Link]()) Prints the last 5 rows of the dataset. Useful to see if data
ends correctly.
print([Link]()) Prints the first 5 rows. Most commonly used to get a quick
look.
print([Link]()) Prints statistics: count, mean, std dev, min, 25%, 50%,
75%, max for each numeric column.
print([Link]()) Prints column names, data types, and non-null counts.
Shows the structure of the data.
print([Link]().sum()) Counts missing (NaN) values per column. isna() returns
True/False; sum() counts the Trues.

🧠 head vs tail
head() = first 5 rows (top of table) | tail() = last 5 rows (bottom of table) Think: head = face,
tail = end.

Step 4 — Clean Data


💻 Code 📖 What it does / Why it's used
df1 = [Link]() Drops all rows with any missing values. Stores clean data
in df1.
💻 Code 📖 What it does / Why it's used
print(df.drop_duplicates(subse Shows only unique species names — removes duplicate
t=['species'])) species rows. subset means only check that column for
duplicates.

🚢 Practical 3
Titanic Dataset — Visualization & Analysis

Practical 3 — Titanic Visualization


Goal: Load the Titanic dataset, clean it, and create 4 types of visualizations: Count Plot, Scatter Plot,
KDE/Density Plot, and Pair Plot.

Step 1 — Import Libraries


💻 Code 📖 What it does / Why it's used
import pandas as pd Pandas for data tables.
import seaborn as sns Seaborn for statistical charts.
import [Link] as Matplotlib for displaying charts.
plt

Step 2 — Load & Clean Data


💻 Code 📖 What it does / Why it's used
data = Loads the built-in Titanic dataset from Seaborn. No CSV
sns.load_dataset("titanic") file needed!
data = Removes rows where age, fare, sex, or survived is
[Link](subset=['age', missing. Only keeps rows that have all 4 values.
'fare', 'sex', 'survived'])

💡 Why subset in dropna?


Without subset, dropna removes rows with ANY missing value in any column. subset limits it
to only the columns you care about — so you don't lose too much data.
Chart 1 — Count Plot (Survival by Gender)
💻 Code 📖 What it does / Why it's used
[Link]() Creates a new blank figure/canvas for the chart.
[Link](x='sex', Draws a bar chart counting male/female passengers, split
hue='survived', data=data) by survived (0=No, 1=Yes). hue adds color-coding by
survived.
[Link]("Survival Count by Adds a title at the top of the chart.
Gender")
[Link]("Gender") Labels the X-axis.
[Link]("Count") Labels the Y-axis.
[Link](title='Survived', Adds a legend showing which color means survived/not
labels=['No', 'Yes']) survived.
[Link]() Displays the chart.

🧠 countplot keyword
countplot → counts occurrences and makes bars hue → splits bars by a second category
(adds color groups)

Chart 2 — Scatter Plot (Age vs Fare)


💻 Code 📖 What it does / Why it's used
[Link]() New blank canvas.
[Link](x='age', Plots each passenger as a dot: X = age, Y = fare paid.
y='fare', hue='survived', Color shows if they survived.
data=data)
[Link]("Scatter Plot: Age Chart title.
vs Fare")
[Link]("Age") X-axis label.
[Link]("Fare") Y-axis label.
[Link](title='Survived') Adds legend for survived colors.
[Link]() Displays the chart.

💡 What does a Scatter Plot show?


Each dot = one person. You can see if older passengers paid more, or if fare affected
survival. Look for patterns or clusters of dots.
Chart 3 — KDE / Density Plot (Age & Fare Distribution)
💻 Code 📖 What it does / Why it's used
[Link]() New blank canvas.
[Link](data=data['age'], Draws a smooth density curve for Age. fill=True shades the
label='Age', fill=True) area under the curve. Shows where most passengers'
ages were concentrated.
[Link](data=data['fare'], Same thing for Fare — shows how fare amounts were
label='Fare', fill=True) distributed. Both curves appear on the same chart.
[Link]("Density Chart title.
Distribution of Age and Fare")
[Link]("Values") X-axis label.
[Link]("Density") Y-axis label — 'density' means probability, not count.
[Link]() Adds a legend to distinguish Age curve from Fare curve.
[Link]() Shows the chart.

🧠 KDE = Kernel Density Estimate


Think of KDE as a smoothed histogram. Instead of bars, it draws a smooth curve showing
where values cluster. fill=True makes it look like a mountain with colored area.

Chart 4 — Pair Plot (All Relationships at Once)


💻 Code 📖 What it does / Why it's used
[Link](data[['age', Creates a grid of scatter plots for every combination of age,
'fare', 'pclass', fare, pclass, survived. Diagonal shows distribution of each
'survived']], hue='survived') variable. hue colors points by survived. Automatically calls
[Link]() internally.
[Link]() Ensures the pair plot is displayed.

🧠 Pair Plot — What to look for?


Diagonal = histogram of each variable Off-diagonal = scatter between two variables Colors =
survived (blue) vs not survived (orange)

⚡ Quick Cheat Sheet


Most important functions across all 3 practicals
Quick Reference Cheat Sheet

💻 Code 📖 What it does / Why it's used


pd.read_csv('[Link]') Load CSV file into DataFrame
[Link] Returns (rows, cols)
[Link]() Count non-null values per column
df.drop_duplicates() Remove duplicate rows
[Link]() Remove rows with missing values
[Link]().sum() Count missing values per column
[Link]() Summary statistics (mean, std, min, max...)
[Link]() Column types and null info
[Link]() / [Link]() First/Last 5 rows
[Link](col, 25) Get Q1 (25th percentile)
[Link](col, 75) Get Q3 (75th percentile)
[Link](col2, Pearson correlation between two columns
method='pearson')
[Link](numeric_only=True) Full correlation matrix
[Link](df_corr, Draw heatmap of correlation matrix
annot=True)
[Link](x=..., hue=...) Count bar chart, colored by category
[Link](x=..., y=..., Scatter plot colored by category
hue=...)
[Link](data=..., Smooth density curve
fill=True)
[Link](df, hue=...) Grid of scatter plots for all column pairs
[Link]() Create a new blank chart
[Link]() Display the chart
[Link]() / [Link]() / Add title and axis labels
[Link]()
[Link]() Show the legend

✅ Study Tip: Write out the code once by hand — muscle memory is the best way to memorize
code!

You might also like