Back to Home 18 lessons + exercises Pyodide ready

Python Data Science
From Data to Insights

Master the complete data science workflow with Python: NumPy, Pandas, data visualization, exploratory data analysis, and machine learning basics. 18 lessons, common mistakes, and hands-on exercises by @PoeticGlenn.

What you will learn

Master the entire data science pipeline: numerical computing with NumPy, data manipulation with Pandas, creating stunning visualizations with Matplotlib and Seaborn, cleaning and preparing data, exploratory data analysis, and building your first machine learning models with scikit-learn — all with step‑by‑step explanations and runnable code from @PoeticGlenn.

🐍 Interactive Python Code Editor

Write, edit, and run Python code directly in your browser. No setup required — powered by Pyodide.

Ready
Examples: Hello World NumPy Array Pandas DataFrame Matplotlib Plot Linear Regression
Tip: Use the example snippets to get started, or write your own Python code. The editor supports NumPy, Pandas, Matplotlib, and scikit-learn.

Why Data Science is the Most Exciting Field of the 21st Century

Data is the new oil — and Python is the refinery. Every organisation, from startups to Fortune 500 companies, is sitting on mountains of data. The ability to extract insights, make predictions, and drive decisions from that data is one of the most valuable skills in the modern economy. Data science isn't just a job title — it's a fundamental competency that enhances every role in technology.

This curriculum, crafted by @PoeticGlenn, takes you from zero to a working knowledge of the entire data science pipeline. You'll learn the tools and techniques used by professionals: NumPy for numerical computing, Pandas for data manipulation, Matplotlib and Seaborn for visualization, and scikit-learn for machine learning. Every concept is explained step‑by‑step with interactive code you can run right in your browser.

Data Wrangling

Learn to clean, transform, and prepare data for analysis using Pandas and NumPy — 80% of a data scientist's time is spent here.

Visual Storytelling

Create compelling visualizations that communicate insights clearly and persuasively to both technical and non‑technical audiences.

Predictive Power

Build machine learning models that learn from data and make predictions — from linear regression to classification algorithms.

This isn't just a tutorial — it's a complete toolkit for turning raw data into actionable insights. Every lesson is designed to give you practical, industry‑tested skills that you can apply immediately. 📊

From Statistics to Artificial Intelligence — The Evolution of Data Science

Data science didn't appear overnight. It's the culmination of centuries of statistical thinking, decades of computer science, and the explosion of big data. Understanding this history helps you appreciate the power of the tools you're about to learn.

1663 — John Graunt

Graunt analysed mortality records in London, creating the first statistical analysis of demographic data — the birth of data-driven decision making.

1800s — Statistics Emerges

Gauss, Laplace, and others develop the mathematical foundations of statistics: least squares, probability theory, and the normal distribution.

1950s — Computer Age

Mainframe computers enable large‑scale data processing. IBM introduces the first hard disk drives, making data storage practical.

1970s — Relational Databases

Edgar Codd introduces the relational model, and SQL becomes the standard for querying structured data. Data storage becomes organised.

1990s — Data Mining

As data grows, the field of data mining emerges. Algorithms like decision trees and neural networks are applied to large datasets.

2000s — Big Data

Google, Amazon, and Facebook generate unprecedented amounts of data. Hadoop and MapReduce make distributed data processing possible.

2010s — The Python Revolution

Python becomes the dominant language for data science. Libraries like NumPy, Pandas, Matplotlib, and scikit-learn make data analysis accessible to everyone.

Today — AI & Beyond

Data science merges with artificial intelligence. Deep learning, natural language processing, and computer vision are transforming every industry.

@PoeticGlenn says: "Data science is the bridge between raw data and human understanding. Every dataset tells a story — and Python gives you the tools to tell it."

How Data Science Powers Today's Technology

Data science is everywhere — from the recommendations you see on Netflix to the fraud detection that protects your bank account. Here's how it's transforming the tech landscape.

E‑commerce & Retail

Recommendation engines, personalised marketing, demand forecasting, and price optimisation — all driven by data science.

Healthcare

Medical imaging analysis, drug discovery, patient outcome prediction, and personalised medicine are revolutionising healthcare.

Autonomous Vehicles

Self‑driving cars rely on data science for perception, decision making, and path planning — processing millions of data points per second.

Finance & Banking

Fraud detection, algorithmic trading, credit scoring, and risk assessment are all powered by sophisticated data science models.

Entertainment

Content recommendation, personalised playlists, and audience analytics keep platforms like Netflix, Spotify, and YouTube engaging.

IoT & Manufacturing

Predictive maintenance, quality control, and supply chain optimisation use data science to reduce downtime and improve efficiency.

The skills you'll learn in this curriculum are applicable across every industry — the demand for data scientists has never been higher.

Data Science is the New Superpower for Developers

Whether you're a web developer, a mobile engineer, or a DevOps specialist, data science skills will make you more valuable and versatile. Here's why every programmer should master this curriculum.

📈 Data‑Driven Decision Making

Learn to back your decisions with data. Instead of guessing, you'll use evidence and analysis to guide product development, feature prioritisation, and system design.

🧠 Think Statistically

Data science teaches you to think in terms of distributions, probabilities, and correlations. This mindset improves debugging, testing, and system design.

🔧 Full‑Stack Data Skills

From data ingestion to visualisation to machine learning, you'll build a complete toolkit that lets you own the entire data pipeline.

💼 Career Acceleration

Data science is consistently ranked as one of the most in‑demand skills. Adding it to your resume opens doors to higher salaries and more interesting roles.

@PoeticGlenn says: "Data science isn't just for data scientists. Every developer who can analyse data becomes a more effective problem solver and a more valuable team member."

Why Data Science is a Cornerstone of Modern Software

In the modern programming ecosystem, data science is not a niche specialisation — it's a core competency. From product analytics to A/B testing to user behaviour analysis, data science informs every aspect of software development.

DevOps & SRE

Analysing system metrics, predicting failures, and optimising performance all require data science techniques. Observability is built on data.

Product & UX

Understanding user behaviour through data analysis drives product decisions. Feature usage, user journeys, and retention are all data‑driven.

Security

Anomaly detection, threat intelligence, and fraud prevention rely heavily on statistical analysis and machine learning.

The curriculum you're about to explore is the practical foundation used by thousands of companies to build data‑driven products and services.

🔢 NumPy — Numerical Computing in Python

NumPy is the foundation of data science in Python. It provides powerful N‑dimensional arrays and fast mathematical operations.

🔢 1.1 Creating and Using NumPy Arrays

NumPy arrays are like Python lists but faster and more memory‑efficient, with built‑in mathematical functions.

Step-by-step explanation:

  • Step 1: Import NumPy as np — this is the standard convention.
  • Step 2: Create an array from a list using np.array().
  • Step 3: Use built‑in functions: np.zeros(), np.ones(), np.arange().
  • Step 4: Access elements using indexing (same as lists).
  • Step 5: Perform arithmetic operations on entire arrays (vectorization).
python
import numpy as np

arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.zeros(5)
arr3 = np.ones(3)
arr4 = np.arange(0, 10, 2)

print("Array from list:", arr1)
print("Zeros:", arr2)
print("Ones:", arr3)
print("Arange:", arr4)

print("First element:", arr1[0])
print("Last element:", arr1[-1])

print("arr1 + 10:", arr1 + 10)
print("arr1 * 2:", arr1 * 2)
print("arr1 ** 2:", arr1 ** 2)

print("Shape:", arr1.shape)
print("Size:", arr1.size)
print("Dtype:", arr1.dtype)
Vectorized operations are much faster than Python loops. Always use NumPy's built‑in operations when working with large datasets.
⚠️ Common mistake: Forgetting the import keyword (e.g., writing rt numpy as np) or misspelling numpy. Also, forgetting square brackets when creating 2D arrays: np.array([ [1,2], [3,4] ]) not np.array([1,2],[3,4]).

🔢 1.2 2D Arrays and Basic Statistics

NumPy supports multi‑dimensional arrays. You can compute statistics like mean, median, and standard deviation easily.

Step-by-step explanation:

  • Step 1: Create a 2D array (matrix) using nested lists.
  • Step 2: Access rows and columns using indexing.
  • Step 3: Compute statistics: mean(), median(), std().
  • Step 4: Use axis parameter to compute along rows or columns.
python
import numpy as np

matrix = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])
print("Matrix:\n", matrix)

print("Row 0:", matrix[0])
print("Column 1:", matrix[:, 1])
print("Element at (1, 2):", matrix[1, 2])

print("Mean:", np.mean(matrix))
print("Median:", np.median(matrix))
print("Standard deviation:", np.std(matrix))
print("Sum:", np.sum(matrix))

print("Mean of each column:", np.mean(matrix, axis=0))
print("Mean of each row:", np.mean(matrix, axis=1))

flat = np.arange(12)
reshaped = flat.reshape(3, 4)
print("Reshaped:\n", reshaped)
axis=0 operates along columns (vertical), axis=1 operates along rows (horizontal).
⚠️ Common mistake: Missing the outer square brackets when defining a matrix — np.array([1,2,3],[4,5,6]) is invalid; use np.array([[1,2,3],[4,5,6]]). Also, confusing axis=0 and axis=1.

📊 Pandas Series — One‑Dimensional Data

A Series is a one‑dimensional array with labels (index). It's like a dictionary and a list combined.

📊 2.1 Creating and Using Series

Series can be created from lists, dictionaries, or NumPy arrays. They have powerful indexing and data manipulation capabilities.

Step-by-step explanation:

  • Step 1: Import Pandas as pd.
  • Step 2: Create a Series from a list or dictionary.
  • Step 3: Access values by index label or position.
  • Step 4: Perform operations like filtering and mathematical functions.
  • Step 5: Use .describe() for summary statistics.
python
import pandas as pd

s1 = pd.Series([10, 20, 30, 40, 50])
print("Series from list:\n", s1)

s2 = pd.Series([85, 92, 78, 90], index=["Alice", "Bob", "Charlie", "Diana"])
print("\nSeries with custom index:\n", s2)

print("\nAlice's score:", s2["Alice"])
print("First value:", s2.iloc[0])

s3 = pd.Series({"Math": 90, "Science": 85, "English": 88})
print("\nSeries from dict:\n", s3)

print("\nScores + 5:\n", s2 + 5)
print("Mean:", s2.mean())
print("Summary:\n", s2.describe())
loc uses index labels, iloc uses integer positions. This distinction is important when working with DataFrames.
⚠️ Common mistake: Using rt pandas as pd instead of import pandas as pd. Also, forgetting to import Pandas before using pd.Series.

📋 Pandas DataFrame — Two‑Dimensional Data

A DataFrame is a 2D table with rows and columns — like a spreadsheet or SQL table. It's the most important data structure in Pandas.

📋 3.1 Creating and Exploring DataFrames

DataFrames can be created from dictionaries, lists, NumPy arrays, or read from CSV files.

Step-by-step explanation:

  • Step 1: Create a DataFrame from a dictionary of lists.
  • Step 2: View the data with .head(), .tail(), and .info().
  • Step 3: Access columns and rows using indexing.
  • Step 4: Use .describe() for statistical summary.
  • Step 5: Filter data using boolean conditions.
python
import pandas as pd

data = {
    "Name": ["Alice", "Bob", "Charlie", "Diana", "Eve"],
    "Age": [25, 30, 35, 28, 32],
    "City": ["NYC", "LA", "Chicago", "SF", "Boston"],
    "Salary": [70000, 85000, 60000, 90000, 75000]
}
df = pd.DataFrame(data)
print("DataFrame:\n", df)

print("\nFirst 3 rows:\n", df.head(3))
print("\nInfo:\n")
df.info()
print("\nDescribe:\n", df.describe())

print("\nNames column:\n", df["Name"])
print("\nMultiple columns:\n", df[["Name", "Salary"]])

print("\nRow 0:\n", df.iloc[0])
print("\nRows 0-2:\n", df.iloc[0:3])

print("\nSalary > 70000:\n", df[df["Salary"] > 70000])

print("\nAge >= 30 and City = LA:\n", df[(df["Age"] >= 30) & (df["City"] == "LA")])
.info() shows column types and non‑null counts — essential for understanding your data before analysis.
⚠️ Common mistake: Using df['Name'] works, but df.Name may fail if the column name has spaces or conflicts with methods. Also, forgetting the double brackets when selecting multiple columns: df[['Name','Salary']] not df['Name','Salary'].

🧹 Data Cleaning — Preparing Data for Analysis

Real data is messy. Learn to handle missing values, remove duplicates, and fix data types.

🧹 4.1 Handling Missing Values

Missing data is common. Pandas provides .isnull(), .dropna(), and .fillna() to handle it.

Step-by-step explanation:

  • Step 1: Create a DataFrame with missing values (np.nan).
  • Step 2: Use .isnull() to detect missing values.
  • Step 3: Use .dropna() to remove rows with missing values.
  • Step 4: Use .fillna() to replace missing values with a default.
  • Step 5: Use .drop_duplicates() to remove duplicate rows.
python
import pandas as pd
import numpy as np

df = pd.DataFrame({
    "A": [1, 2, np.nan, 4, 5],
    "B": [10, np.nan, 30, 40, 50],
    "C": [100, 200, 300, np.nan, 500]
})
print("Original:\n", df)

print("\nIs null?\n", df.isnull())
print("\nMissing count:\n", df.isnull().sum())

print("\nDrop rows with missing values:\n", df.dropna())

print("\nDrop rows where all missing:\n", df.dropna(how="all"))

print("\nFill with 0:\n", df.fillna(0))
print("\nFill with mean of each column:\n", df.fillna(df.mean()))

df_dup = pd.DataFrame({"X": [1, 2, 2, 3, 3, 3], "Y": ["a", "b", "b", "c", "c", "c"]})
print("\nWith duplicates:\n", df_dup)
print("\nWithout duplicates:\n", df_dup.drop_duplicates())
Always understand why data is missing before removing or filling it. Sometimes missing values carry important information.
⚠️ Common mistake: Using np.nan without importing NumPy. Also, forgetting that dropna() returns a new DataFrame, not modifying the original unless inplace=True.

🔍 Exploratory Data Analysis (EDA)

EDA is the process of understanding your data through summary statistics, visualisations, and pattern discovery.

🔍 5.1 Summary Statistics and Grouping

Use .describe(), .groupby(), and .value_counts() to explore your data.

Step-by-step explanation:

  • Step 1: Load or create a DataFrame with categorical and numerical columns.
  • Step 2: Use .describe() for numerical summary.
  • Step 3: Use .value_counts() for categorical frequencies.
  • Step 4: Use .groupby() to aggregate data by categories.
  • Step 5: Use .pivot_table() for cross‑tabulation.
python
import pandas as pd
import numpy as np

data = {
    "Department": ["Sales", "Sales", "IT", "IT", "Sales", "IT", "HR", "HR"],
    "Employee": ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank", "Grace", "Henry"],
    "Salary": [70000, 65000, 85000, 90000, 72000, 88000, 60000, 62000],
    "Experience": [5, 3, 8, 10, 4, 9, 2, 3]
}
df = pd.DataFrame(data)

print("Summary (numerical):\n", df.describe())
print("\nSummary (categorical):\n", df.describe(include=["object"]))

print("\nDepartment counts:\n", df["Department"].value_counts())

print("\nAverage salary by department:\n", df.groupby("Department")["Salary"].mean())
print("\nAggregate functions:\n", df.groupby("Department")["Salary"].agg(["mean", "min", "max"]))

print("\nPivot table:\n", df.pivot_table(values="Salary", index="Department", columns="Experience", aggfunc="mean"))
groupby() is one of the most powerful tools in Pandas. It lets you split data, apply functions, and combine results — the "split‑apply‑combine" pattern.
⚠️ Common mistake: Forgetting to include the column name after groupby when aggregating, e.g., df.groupby('Department').mean() works on all numeric columns, but may include unwanted columns.

📈 Data Visualization with Matplotlib

Matplotlib is the foundational plotting library in Python. Learn to create line plots, bar charts, histograms, and scatter plots.

📈 6.1 Creating Basic Plots

Matplotlib's pyplot module provides a MATLAB‑like interface for creating plots.

Step-by-step explanation:

  • Step 1: Import matplotlib.pyplot as plt.
  • Step 2: Create data for plotting.
  • Step 3: Use plt.plot() for line plots, plt.bar() for bar charts.
  • Step 4: Add labels, title, and legend.
  • Step 5: Use plt.show() to display (simulated in browser).
python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

plt.figure(figsize=(10, 6))

plt.plot(x, y1, label="sin(x)", color="blue", linewidth=2)
plt.plot(x, y2, label="cos(x)", color="orange", linewidth=2, linestyle="--")

plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.title("Sine and Cosine Functions")
plt.legend()
plt.grid(True, alpha=0.3)

print("Plot created successfully!")
print("(In a real environment, plt.show() would display the plot)")

categories = ["A", "B", "C", "D"]
values = [25, 40, 30, 55]
plt.figure(figsize=(8, 5))
plt.bar(categories, values, color="teal")
plt.title("Bar Chart Example")
plt.xlabel("Categories")
plt.ylabel("Values")
print("\nBar chart created!")

data = np.random.normal(100, 15, 1000)
plt.figure(figsize=(8, 5))
plt.hist(data, bins=30, color="purple", alpha=0.7)
plt.title("Histogram of Normally Distributed Data")
plt.xlabel("Value")
plt.ylabel("Frequency")
print("\nHistogram created!")
In the browser environment, plots are created but not displayed. In a local Jupyter environment, plt.show() would render them.
⚠️ Common mistake: Forgetting to call plt.figure() before plotting, which can cause plots to overlap. Also, using plt.show() in a non‑interactive environment may not work — in Pyodide, we just create the figures without display.

🎨 Seaborn — Statistical Data Visualization

Seaborn builds on Matplotlib to create beautiful, informative statistical visualizations with less code.

🎨 7.1 Seaborn Plots

Seaborn provides high‑level functions for common statistical plots: scatter plots, pair plots, heatmaps, and more.

Step-by-step explanation:

  • Step 1: Import seaborn as sns.
  • Step 2: Load or create a dataset.
  • Step 3: Use sns.scatterplot() for scatter plots.
  • Step 4: Use sns.pairplot() to visualize relationships between all numerical variables.
  • Step 5: Use sns.heatmap() for correlation matrices.
python
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(42)
data = pd.DataFrame({
    "Feature_A": np.random.randn(100) * 10 + 50,
    "Feature_B": np.random.randn(100) * 8 + 60,
    "Feature_C": np.random.randn(100) * 12 + 40,
    "Target": np.random.randn(100) * 5 + 70
})

sns.set_style("darkgrid")
print("Seaborn style set")

plt.figure(figsize=(8, 6))
sns.scatterplot(data=data, x="Feature_A", y="Target", color="teal")
plt.title("Scatter Plot: Feature A vs Target")
print("\nScatter plot created")

print("\nPair plot would show all pairwise relationships")
print("(In a real environment, sns.pairplot(data) would display)")

plt.figure(figsize=(8, 6))
corr = data.corr()
sns.heatmap(corr, annot=True, cmap="coolwarm", center=0)
plt.title("Correlation Heatmap")
print("\nHeatmap created")

plt.figure(figsize=(8, 5))
sns.histplot(data["Target"], bins=30, kde=True, color="purple")
plt.title("Distribution of Target Variable")
print("\nDistribution plot created")
Seaborn's integration with Pandas makes it easy to create complex visualizations in just one line of code.
⚠️ Common mistake: Forgetting to import Seaborn or using rt seaborn as sns instead of import seaborn as sns. Also, not setting the style before plotting can lead to default Matplotlib styles.

📉 Linear Regression — Predicting Continuous Values

Linear regression is the foundation of predictive modeling. Learn to use scikit‑learn to build and evaluate regression models.

📉 8.1 Building a Linear Regression Model

Use LinearRegression from scikit‑learn to fit a model to your data and make predictions.

Step-by-step explanation:

  • Step 1: Import LinearRegression from sklearn.linear_model.
  • Step 2: Split data into features (X) and target (y).
  • Step 3: Split into training and test sets using train_test_split.
  • Step 4: Create and train the model with .fit().
  • Step 5: Make predictions with .predict() and evaluate using r2_score.
python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_squared_error

np.random.seed(42)
X = np.random.randn(100, 1) * 10 + 20
y = 3 * X.flatten() + 7 + np.random.randn(100) * 3

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

model = LinearRegression()
model.fit(X_train, y_train)
print("Model trained")

y_pred = model.predict(X_test)

print(f"Coefficient (slope): {model.coef_[0]:.4f}")
print(f"Intercept: {model.intercept_:.4f}")
print(f"R² Score: {r2_score(y_test, y_pred):.4f}")
print(f"RMSE: {np.sqrt(mean_squared_error(y_test, y_pred)):.4f}")

new_x = np.array([[30]])
prediction = model.predict(new_x)
print(f"\nPrediction for X=30: {prediction[0]:.2f}")
The R² score measures how well the model explains the variance in the data. Values closer to 1 indicate better performance.
⚠️ Common mistake: Forgetting that X must be a 2D array (even if one feature). Using X.reshape(-1,1) if needed. Also, not splitting data before fitting leads to overfitting.

🏷️ Classification — Predicting Categories

Classification models predict discrete categories. Learn to build a logistic regression model for binary classification.

🏷️ 9.1 Building a Classification Model

Use LogisticRegression to classify data into two or more categories.

Step-by-step explanation:

  • Step 1: Import LogisticRegression and evaluation metrics.
  • Step 2: Create synthetic data with two classes.
  • Step 3: Split into training and test sets.
  • Step 4: Train the model and make predictions.
  • Step 5: Evaluate using accuracy, precision, and recall.
python
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score, classification_report

np.random.seed(42)
X = np.random.randn(200, 2)
y = (X[:, 0] + X[:, 1] > 0).astype(int)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

model = LogisticRegression()
model.fit(X_train, y_train)
print("Model trained")

y_pred = model.predict(X_test)

print(f"Accuracy: {accuracy_score(y_test, y_pred):.4f}")
print(f"Precision: {precision_score(y_test, y_pred):.4f}")
print(f"Recall: {recall_score(y_test, y_pred):.4f}")
print("\nClassification Report:")
print(classification_report(y_test, y_pred))

new_sample = np.array([[1.0, -0.5]])
pred = model.predict(new_sample)
prob = model.predict_proba(new_sample)
print(f"\nNew sample {new_sample.flatten()} → Class: {pred[0]}, Probabilities: {prob[0]}")
Accuracy isn't always the best metric. For imbalanced datasets, precision and recall are more informative.
⚠️ Common mistake: Using LogisticRegression for multi‑class without setting multi_class parameter; but for binary it's fine. Also, forgetting to scale features when needed.

🚀 Real‑World Project: Complete Data Science Workflow

Bring everything together in a complete data science project: data loading, cleaning, EDA, visualization, and modeling.

🚀 10.1 End‑to‑End Data Science Project

We'll simulate a real‑world project: analysing a dataset, building visualizations, and training a model to predict a target variable.

Step-by-step explanation:

  • Step 1: Load and explore the data.
  • Step 2: Clean and preprocess the data (handle missing values).
  • Step 3: Perform EDA with summary statistics and visualizations.
  • Step 4: Split data and train a model.
  • Step 5: Evaluate and interpret the results.
python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score

np.random.seed(42)
n = 150
data = pd.DataFrame({
    "Square_Feet": np.random.randn(n) * 500 + 2000,
    "Bedrooms": np.random.randint(1, 6, n),
    "Age": np.random.randint(0, 30, n),
    "Price": np.random.randn(n) * 50000 + 350000
})
data.loc[10:15, "Bedrooms"] = np.nan

print("=== 1. Data Overview ===")
print(data.head())
print(f"\nShape: {data.shape}")
print(f"Missing values:\n{data.isnull().sum()}")

data["Bedrooms"] = data["Bedrooms"].fillna(data["Bedrooms"].median())
print(f"\nMissing values after cleaning:\n{data.isnull().sum()}")

print("\n=== 2. EDA ===")
print(data.describe())

corr = data.corr()
print("\nCorrelations with Price:")
print(corr["Price"].sort_values(ascending=False))

X = data[["Square_Feet", "Bedrooms", "Age"]]
y = data["Price"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

print("\n=== 3. Model Results ===")
print(f"R² Score: {r2_score(y_test, y_pred):.4f}")
print(f"Coefficients:\n{model.coef_}")
print(f"Intercept: {model.intercept_:.2f}")

print("\nFull data science workflow completed!")
print("(In a real project, you would also tune hyperparameters and perform cross‑validation)")
This workflow — load, clean, explore, model, evaluate — is the same pattern used in real‑world data science projects. Master it, and you can tackle any dataset.

✏️ Practice Exercises

Test your skills with these hands‑on exercises. Try to solve them using the code editor above.

📝 Exercise 1 – NumPy Basics

Create a 5x5 NumPy array filled with random integers between 0 and 100. Compute the mean, standard deviation, and the sum of each row.

📝 Exercise 2 – Pandas Series

Create a Pandas Series from a dictionary of five countries and their populations (in millions). Sort the series by population descending and print the country with the highest population.

📝 Exercise 3 – DataFrame Manipulation

Given a DataFrame with columns Product, Sales, Region, group by Region and compute the total sales per region. Then filter to show only regions with total sales above 1000.

📝 Exercise 4 – Data Cleaning

Load the built‑in Iris dataset (from sklearn.datasets import load_iris). Convert to a DataFrame, check for missing values (none actually), but add some artificially and then fill them with the mean of each column.

📝 Exercise 5 – Linear Regression

Using the Boston housing dataset (or a synthetic one), train a linear regression model. Split data, train, and report R² and RMSE. Experiment with different test sizes.

📝 Exercise 6 – Classification

Using the breast cancer dataset from sklearn.datasets, build a logistic regression model. Evaluate using accuracy, precision, recall, and plot the confusion matrix (use seaborn heatmap).

Tips: Use the interactive code editor above to write and test your solutions. If you get stuck, review the corresponding lesson or ask for help in the community.

❓ Frequently Asked Questions — Data Science

Common questions about Python data science, answered.

Do I need to know statistics to do data science?

+

Basic statistics (mean, median, standard deviation, correlation) is essential. This curriculum covers the fundamentals. More advanced statistics can be learned as you progress.

What's the difference between Pandas and NumPy?

+

NumPy provides fast numerical arrays and mathematical operations. Pandas builds on NumPy to provide higher‑level data structures (Series, DataFrame) with labels and more intuitive data manipulation.

Which is better: Matplotlib or Seaborn?

+

They're complementary. Matplotlib is more flexible and lower‑level. Seaborn is built on Matplotlib and provides beautiful statistical visualizations with less code. Most data scientists use both.

What is scikit‑learn used for?

+

Scikit‑learn is the most popular library for machine learning in Python. It provides tools for preprocessing, model training, evaluation, and hyperparameter tuning for both supervised and unsupervised learning.

How do I choose the right algorithm for my data?

+

It depends on your problem: regression for continuous targets, classification for categories, clustering for grouping without labels. Always start with simple models and increase complexity as needed.

What is overfitting and how do I avoid it?

+

Overfitting happens when a model learns noise instead of patterns. Avoid it by using cross‑validation, simplifying the model, and using regularization. Always evaluate on a separate test set.

💛 You've Completed the Data Science Journey

From NumPy arrays to machine learning models, you've built a complete data science toolkit. You've learned to load, clean, explore, visualise, and model data — the entire pipeline that powers data‑driven decision making.


📌 What You've Mastered

  • ✅ NumPy arrays & vectorization
  • ✅ Pandas Series & DataFrames
  • ✅ Data cleaning & preprocessing
  • ✅ Exploratory data analysis
  • ✅ Matplotlib & Seaborn visualizations
  • ✅ Linear regression with scikit‑learn
  • ✅ Classification with logistic regression
  • ✅ Model evaluation (R², accuracy, precision, recall)
  • ✅ End‑to‑end data science workflow

🚀 Next Steps

  • Practice: Re‑do the exercises with different datasets.
  • Explore Kaggle: Apply your skills to real‑world competitions.
  • Dive deeper: Learn about feature engineering, hyperparameter tuning, and ensemble methods.
  • Learn SQL: Combine data science with database querying.
  • Study statistics: Deepen your understanding of hypothesis testing and probability.

📚 Recommended Resources


Data science is the art of turning data into decisions. Master it, and you become the bridge between information and action. — Glenn Junsay Pansensoy (@PoeticGlenn)