Python DataScience Complete Guide
Python DataScience Complete Guide
DATA SCIENCE
Complete Mastery Guide — Beginner to Advanced
NumPy Pandas Matplotlib Scikit-Learn TensorFlow Deep Learning
■ NumPy & Pandas Mastery ■ ML & Deep Learning ■ NLP & Computer Vision
■ TABLE OF CONTENTS
Chapter 1
Python dominates data science, machine learning and AI because of its readable syntax, massive
ecosystem, and world-class community. Companies like Google, Netflix, Uber and NASA rely on
Python for data pipelines and ML systems. Learning Python for data science opens doors to one of
the highest-paying career paths in tech.
MATLAB ■■ ■■ ■■■ ■■
Anaconda bundles Python 3.10+, Jupyter, and 250+ pre-installed packages. It is the recommended
setup for data scientists at every level.
Python
# Verify installation
import sys
print(f'Python: {[Link]}')
NOTE
Always isolate project dependencies in a virtual environment. This prevents
version conflicts and makes projects reproducible.
Python
# conda — recommended
conda create -n ds_env python=3.11
conda activate ds_env
conda install numpy pandas matplotlib seaborn scikit-learn
pip install tensorflow torch jupyter
# venv alternative
python -m venv myenv
source myenv/bin/activate # Linux/macOS
myenv\Scripts\activate # Windows
Jupyter is the standard tool for interactive data exploration. You write code in cells, see results inline,
and weave in Markdown explanations — perfect for sharing analyses.
Python
# Keyboard shortcuts
# Shift+Enter → Run cell & go to next
# Ctrl+Enter → Run cell, stay
# A / B → Insert cell Above / Below
# M / Y → Markdown / Code mode
# DD → Delete cell
# Ctrl+Z → Undo in cell
TIP
Use JupyterLab for a full IDE experience: file browser, terminal, multiple tabs,
git integration, and rich extension ecosystem.
Chapter 2
Python is dynamically typed — no type declarations needed. Variables are created on assignment
and can be reassigned to any type. This flexibility speeds up development but requires discipline in
data science to avoid silent type errors.
Python
# Variable assignment
name = 'Alice' # str
age = 28 # int
height = 1.72 # float
is_active = True # bool
score = None # NoneType
# Multiple / unpacking
x = y = z = 0 # All equal 0
a, b, c = 1, 2, 3 # Tuple unpack
first, *rest = [1,2,3,4,5] # Extended unpack
# first=1, rest=[2,3,4,5]
# Type checking
print(type(name)) # <class 'str'>
print(isinstance(age, int)) # True
# Type conversion
num_str = '42'
num_int = int(num_str) # 42
num_flt = float(num_str) # 42.0
back = str(num_int) # '42'
Python
s1 = 'single quotes'
s2 = "double quotes"
s3 = """multi
line"""
s4 = r'raw\nstring' # Backslash literal
Python
nums = [1, 2, 3, 4, 5]
mixed = [1, 'hello', 3.14, True, None]
matrix = [[1,2,3],[4,5,6],[7,8,9]] # 2D list
# Mutating
[Link](6) # add to end
[Link](0, 0) # insert at index
[Link](3) # remove first match
[Link]() # remove & return last
[Link]() # sort in-place
sorted(nums) # return new sorted list
KEY CONCEPT
List comprehensions are 2–5× faster than equivalent for-loops and are the standard
Python idiom in data science for building arrays before converting to NumPy.
Python
for k, v in [Link]():
print(f'{k}: {v}')
# Dict comprehension
scores = {'Alice':95,'Bob':87,'Carol':91}
grades = {n: 'A' if s>=90 else 'B'
for n,s in [Link]()}
Chapter 3
3.1 Conditionals
Python
score = 85
if score >= 90: grade = 'A'
elif score >= 80: grade = 'B'
elif score >= 70: grade = 'C'
else: grade = 'F'
# One-liner ternary
result = 'Pass' if score >= 60 else 'Fail'
3.2 Loops
Python
# while loop
n = 10
while n > 0: n -= 2
Python
# List comprehension
squares = [x**2 for x in range(10)]
even_sq = [x**2 for x in range(10) if x%2==0]
# Dict comprehension
word_len = {w: len(w) for w in ['cat','elephant','fox']}
# Set comprehension
unique_sq = {x**2 for x in range(-5, 6)}
Chapter 4
Python
Python
# Decorators
def log(fn):
def wrapper(*a,**kw):
print(f"Calling {fn.__name__}")
return fn(*a,**kw)
return wrapper
@log
def add(x,y): return x+y
Chapter 6
NumPy provides the ndarray — a multidimensional array stored in contiguous memory, processed via
C/Fortran kernels. Operations are vectorized (no Python loops), making NumPy 100–1000× faster
than pure Python for numerical work. Every major data science library is built on NumPy arrays.
1 2 3 4
rows → 5 6 7 8
9 10 11 12
NOTE
NumPy arrays have a fixed data type (dtype) and fixed size. This enables
contiguous memory storage and SIMD (vectorized) CPU instructions — the secret
behind its speed.
Python
import numpy as np
# Creating arrays
a1 = [Link]([1,2,3,4,5]) # 1-D
a2 = [Link]([[1,2,3],[4,5,6]]) # 2-D
a3 = [Link](0, 10, 0.5) # 0..9.5
a4 = [Link](0, 1, 100) # 100 pts
z = [Link]((3,4)) # 3×4 zeros
o = [Link]((2,3,4)) # 3-D ones
I = [Link](4) # Identity
r = [Link](3,3) # Uniform [0,1)
rn = [Link](1000) # Normal
ri = [Link](0,100,(5,5)) # Random ints
# Array properties
arr = [Link]([[1,2,3],[4,5,6]])
print([Link]) # (2, 3)
print([Link]) # 2
print([Link]) # 6
print([Link]) # int64
print([Link]) # 48
Python
import numpy as np
a = [Link]([1,2,3,4])
b = [Link]([10,20,30,40])
# Element-wise — no loops!
print(a + b) # [11 22 33 44]
print(a * b) # [10 40 90 160]
print(a ** 2) # [1 4 9 16]
print([Link](b)) # [3.16 4.47 5.47 6.32]
# Broadcasting
M = [Link]([[1,2,3],[4,5,6],[7,8,9]])
row = [Link]([10,20,30]) # shape (3,)
M + row # [[11,22,33],[14,25,36],[17,28,39]]
Python
arr = [Link](24).reshape(4,6)
# Indexing
print(arr[0,0]) # 0
print(arr[-1,-1]) # 23
print(arr[1,:]) # row 1
print(arr[:,2]) # column 2
print(arr[0:2,0:3]) # sub-matrix
# Fancy indexing
print(arr[[0,2]]) # rows 0 and 2
# Reshape
flat = [Link]() # 1-D copy
view = [Link]() # 1-D view
cube = [Link](2,3,4) # 3-D
T = arr.T # Transpose
Python
import numpy as np
data = [Link]([23,45,12,67,34,89,56,78,43,65])
print(f'Mean : {[Link](data):.2f}')
print(f'Median : {[Link](data):.2f}')
print(f'Std : {[Link](data):.2f}')
print(f'Var : {[Link](data):.2f}')
print(f'Min/Max: {[Link](data)} / {[Link](data)}')
# Linear algebra
A = [Link]([[1,2],[3,4]])
det = [Link](A) # -2.0
inv = [Link](A)
eigv,eigvec = [Link](A)
U,S,Vt = [Link](A) # SVD
Chapter 10
Pandas is the most essential library for data manipulation. It provides two data structures: Series (1-D
labeled array) and DataFrame (2-D labeled table with mixed types). Pandas combines the speed of
NumPy with the convenience of spreadsheet operations.
Alice 23 95.2 A
Bob 25 87.5 B+
Carol 22 92.1 A-
David 24 78.9 C+
Python
import pandas as pd
import numpy as np
# ■■ Series ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
s = [Link]([10,20,30,40], index=['a','b','c','d'])
print(s['a']) # 10
print([Link]) # array([10,20,30,40])
# ■■ DataFrame ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
df = [Link]({
'Name' : ['Alice','Bob','Carol','David'],
'Age' : [23,25,22,24],
'Score': [95.2,87.5,92.1,78.9],
'Dept' : ['CS','Math','CS','Physics']
})
# Inspection
[Link] # (4, 4)
[Link] # data types per column
[Link](3) # first 3 rows
[Link]() # non-null counts + dtypes
[Link]() # count/mean/std/min/q/max
[Link]() # unique values per column
Python
# Column selection
df['Name'] # Single → Series
df[['Name','Score']] # Multiple → DataFrame
# Row selection
[Link][0] # by label
[Link][0:2,'Name':'Score'] # slice by labels
[Link][0] # by integer position
[Link][-1] # last row
Python
# Missing values
[Link]().sum() # NaN count per col
[Link]().mean()*100 # % missing
[Link]() # drop NaN rows
df['Score'].fillna(df['Score'].mean())
[Link](0) # fill all NaN
# Duplicates
[Link]().sum()
df.drop_duplicates()
df.drop_duplicates(subset=['Name'])
# Type conversion
df['Date'] = pd.to_datetime(df['Date'])
df['Score'] = pd.to_numeric(df['Score'], errors='coerce')
# String cleaning
df['Name'] = df['Name'].[Link]().[Link]()
df['Phone'] = df['Phone'].[Link]('-','')
# Rename columns
[Link](columns={'old':'new'}, inplace=True)
[Link] = [Link]().[Link](" ","_")
Python
# GroupBy
dept_stats = [Link]('Dept')['Score'].agg(
mean='mean', std='std', count='count')
# Pivot table
pd.pivot_table(df, values='Score',
index='Dept', columns='Grade',
aggfunc='mean', fill_value=0)
Chapter 15
Matplotlib uses a hierarchy: Figure (canvas) → Axes (plot area) → Artists (lines, labels etc.). Always
use the object-oriented API (fig, ax = [Link]()) for full control.
Python
fig, ax = [Link](figsize=(10,6))
# Multiple subplots
fig, axes = [Link](2, 3, figsize=(15,8))
for i, ax in enumerate([Link]):
[Link]([Link](100).cumsum())
ax.set_title(f'Random Walk {i+1}')
plt.tight_layout()
Python
# 1. Line chart
axes[0,0].plot([1,3,5,7,9],[2,4,3,8,6],'b-o')
axes[0,0].set_title('Line Chart')
# 2. Bar chart
cats=['A','B','C','D']
vals=[25,40,30,55]
axes[0,1].bar(cats, vals, color='#1565C0')
axes[0,1].set_title('Bar Chart')
# 3. Histogram
data = [Link](1000)
axes[0,2].hist(data, bins=30, color='#42A5F5', edgecolor='white')
axes[0,2].set_title('Histogram')
# 4. Scatter plot
x,y = [Link](200),[Link](200)
axes[1,0].scatter(x,y,alpha=0.5,color='#E74C3C')
axes[1,0].set_title('Scatter Plot')
# 5. Box plot
groups = [[Link](100) for _ in range(4)]
axes[1,1].boxplot(groups, labels=['G1','G2','G3','G4'])
axes[1,1].set_title('Box Plot')
# 6. Heatmap (manual)
mat = [Link](6,6)
axes[1,2].imshow(mat, cmap='Blues')
axes[1,2].set_title('Heatmap')
plt.tight_layout()
Python
sns.set_theme(style='whitegrid', palette='husl')
tips = sns.load_dataset('tips') # Built-in dataset
# Distribution
[Link](tips['total_bill'], kde=True)
[Link](x='day', y='total_bill', data=tips)
[Link](x='day', y='tip', hue='sex', data=tips)
# Relationships
[Link](x='total_bill',y='tip',hue='sex',data=tips)
[Link](x='total_bill',y='tip',data=tips) # +regression
# Categorical
[Link](x='day',y='total_bill',data=tips,ci=95)
[Link](x='day',data=tips)
# Correlation heatmap
corr = tips.select_dtypes("number").corr()
[Link](corr, annot=True, fmt='.2f', cmap='coolwarm')
Chapter 18
Python
import pandas as pd
import numpy as np
from scipy import stats
data = [Link]([12,23,34,45,56,23,34,45,67,78,23,45])
# Central tendency
print(f'Mean : {[Link]():.2f}')
print(f'Median : {[Link]():.2f}')
print(f'Mode : {[Link]()[0]}')
# Spread
print(f'Std : {[Link]():.2f}')
print(f'Var : {[Link]():.2f}')
print(f'IQR : {[Link](.75)-[Link](.25):.2f}')
# Shape
print(f'Skew : {[Link]():.2f}') # 0=symmetric
print(f'Kurt : {[Link]():.2f}') # 0=normal
# Full summary
[Link](percentiles=[.1,.25,.5,.75,.9])
Python
import numpy as np
import [Link] as plt
from [Link] import norm, binom, poisson, uniform
# Normal distribution
mu, sigma = 100, 15
x = [Link](50,150,200)
pdf = [Link](x, mu, sigma)
# Binomial
n,p = 10, 0.5 # 10 flips, fair coin
print(f"P(X=5): {[Link](5,n,p):.4f}")
print(f"P(X>=7): {[Link](6,n,p):.4f}")
# Poisson
lam = 3 # avg 3 events/hr
print(f"P(X=5): {[Link](5,lam):.4f}")
Python
# One-sample t-test
# H0: population mean = 100
sample = [Link](102, 15, 50)
t_stat, p_val = stats.ttest_1samp(sample, 100)
print(f't={t_stat:.3f}, p={p_val:.4f}')
conclusion = 'Reject H0' if p_val < 0.05 else 'Fail to reject H0'
# Two-sample t-test
groupA = [Link](50, 10, 30)
groupB = [Link](55, 12, 30)
t, p = stats.ttest_ind(groupA, groupB)
print(f'Two-sample: t={t:.3f}, p={p:.4f}')
# Correlation test
x = [Link](100)
y = 2*x + [Link](100)
r, p = [Link](x, y)
print(f'r={r:.3f}, p={p:.4f}')
NOTE
A p-value < 0.05 means we reject the null hypothesis at 5% significance level.
ALWAYS check assumptions: normality, equal variance, independence, sample size.
Chapter 22
Train Feature ML
Predict
Data Eng. Model
Test Eval
Data Metrics
NOTE
Scikit-Learn follows a universal API: [Link](X_train, y_train) →
.predict(X_test) → .score(X_test, y_test). This works for ALL 100+ algorithms!
Python
# Step 1 — Data
X = [Link](1000, 10)
y = (X[:,0]+X[:,1] > 0).astype(int)
# Step 2 — Split
X_tr,X_te,y_tr,y_te = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y)
# Step 4 — Train
model = LogisticRegression(max_iter=1000)
[Link](X_tr, y_tr)
# Step 5 — Evaluate
y_pred = [Link](X_te)
print(f'Accuracy: {accuracy_score(y_te,y_pred):.4f}')
print(classification_report(y_te,y_pred))
Python
# Clean pipeline
pipe = Pipeline([
('scaler', StandardScaler()),
('clf', RandomForestClassifier(random_state=42))
])
# 5-fold cross-validation
scores = cross_val_score(pipe, X, y, cv=5, scoring='accuracy')
print(f'CV: {[Link]():.4f} ± {[Link]():.4f}')
Python
y_pred = [Link](X_te)
y_proba = model.predict_proba(X_te)[:,1]
print(f'Accuracy : {accuracy_score(y_te,y_pred):.4f}')
print(f'Precision: {precision_score(y_te,y_pred):.4f}')
print(f'Recall : {recall_score(y_te,y_pred):.4f}')
print(f'F1-Score : {f1_score(y_te,y_pred):.4f}')
print(f'ROC-AUC : {roc_auc_score(y_te,y_proba):.4f}')
# Confusion matrix
cm = confusion_matrix(y_te,y_pred)
print(cm)
# [[TN FP]
# [FN TP]]
Chapter 28
A neural network learns by adjusting weights through backpropagation. Input data flows forward
through layers; the error gradient flows backward, updating weights via gradient descent. Activation
functions introduce non-linearity, allowing the network to model complex patterns.
Python
import numpy as np
class NeuralNetwork:
def __init__(self, sizes):
self.W = [[Link](a,b)*0.01
for a,b in zip(sizes[:-1],sizes[1:])]
self.b = [[Link](b) for b in sizes[1:]]
nn = NeuralNetwork([784,256,128,10])
out = [Link]([Link](32,784))
print(f'Output: {[Link]}') # (32, 10)
Python
import tensorflow as tf
from [Link] import layers
# Compile
[Link](
optimizer=[Link](1e-3),
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Callbacks
cbs = [
[Link](patience=5, restore_best_weights=True),
[Link](factor=0.5, patience=3),
]
# Train
history = [Link](
X_train, y_train,
epochs=50, batch_size=64,
validation_split=0.2,
callbacks=cbs
)
Python
# Block 1
x = layers.Conv2D(32,3,padding='same',activation='relu')(inputs)
x = [Link]()(x)
x = layers.MaxPooling2D()(x)
# Block 2
x = layers.Conv2D(64,3,padding='same',activation='relu')(x)
x = [Link]()(x)
x = layers.MaxPooling2D()(x)
# Block 3
x = layers.Conv2D(128,3,padding='same',activation='relu')(x)
x = layers.GlobalAveragePooling2D()(x)
# Classifier
x = [Link](256,activation='relu')(x)
x = [Link](0.5)(x)
outputs = [Link](n_classes,activation='softmax')(x)
return Model(inputs,outputs)
cnn = build_cnn()
[Link]()
Chapter 33
Python
def clean_text(text):
text = [Link]()
text = [Link](r'<.*?>','',text) # strip HTML
text = [Link](r'http\S+','',text) # strip URLs
text = [Link](r'[^a-z0-9 ]','',text) # keep alphanum
tokens = [Link]()
stops = {'the','a','an','is','it','in','to'}
return [t for t in tokens if t not in stops]
corpus = [
"Python is great for data science",
"Machine learning with scikit-learn",
]
[print(clean_text(t)) for t in corpus]
Python
Python
# BERT embeddings
model_name = 'bert-base-uncased'
tokenizer = AutoTokenizer.from_pretrained(model_name)
bert = AutoModel.from_pretrained(model_name)
Chapter 39
Python
# Feature engineering
df["tenure_yr"] = df["tenure_months"]/12
df["chg_per_svc"] = df["monthly_charges"]/(df["num_services"]+1)
num_cols = ["tenure_yr","monthly_charges","chg_per_svc"]
cat_cols = ["contract","internet_service","payment_method"]
pre = ColumnTransformer([
("num", StandardScaler(), num_cols),
("cat", OneHotEncoder(drop="first"), cat_cols)
])
pipe = Pipeline([
("pre", pre),
("model", GradientBoostingClassifier(n_estimators=200))
])
[Link](X_tr, y_tr)
y_proba = pipe.predict_proba(X_te)[:,1]
print(f'ROC-AUC: {roc_auc_score(y_te, y_proba):.4f}')
Pandas GroupBy, merge, pivot, time-series How do you handle missing data?
System Design ML pipeline, A/B test, feature store Design a recommender system
TIP
Top study resources: Hands-On Machine Learning (Géron), [Link], Kaggle
competitions, StatQuest YouTube, and LeetCode SQL problems.