Skip to content
Happy Programming Guide
Start learning
Python

Python and Data Science

The four libraries that matter — NumPy, pandas, matplotlib and scikit-learn — and a complete first analysis from loading a CSV to a finished chart.

A close-up of a printed circuit board

Python dominates data science because of four libraries: NumPy for fast numeric arrays, pandas for tables, matplotlib for charts, and scikit-learn for models. This guide covers what each does and walks through a complete small analysis — load, clean, explore, summarise, plot — which is the shape of most real data work.

Setting up#

Terminal
python -m venv .venv
source .venv/bin/activate        # .venv\Scripts\activate on Windows
pip install numpy pandas matplotlib scikit-learn jupyter

Use a virtual environment. Data science projects accumulate dependencies quickly and version conflicts between them are common.

NumPy: fast arrays#

Python
import numpy as np

a = np.array([1, 2, 3, 4, 5])

print(a * 2)                # [2 4 6 8 10] - no loop needed
print(a[a > 2])             # [3 4 5]      - boolean indexing
print(a.mean(), a.std())

grid = np.zeros((3, 4))
print(grid.shape)           # (3, 4)

The operations run in compiled C, so they are far faster than a Python loop over a list — often by two orders of magnitude on large arrays. Everything else in the stack is built on NumPy arrays.

pandas: tables#

Python
import pandas as pd

df = pd.read_csv("sales.csv")

print(df.head())            # first five rows
print(df.shape)             # (rows, columns)
print(df.info())            # types and non-null counts
print(df.describe())        # numeric summary
print(df.isna().sum())      # missing values per column

Run those five lines before doing anything else, every single time. Most analysis mistakes come from assuming what the data looks like rather than checking.

Selecting#

Python
df["amount"]                      # one column - a Series
df[["date", "amount"]]            # several - a DataFrame

df.loc[0]                         # by label
df.iloc[0]                        # by position
df.loc[df["amount"] > 100]        # filtering
df.loc[(df["amount"] > 100) & (df["region"] == "North")]

Cleaning#

Python
# Missing values
print(df.isna().sum())

df = df.dropna(subset=["amount"])            # drop rows missing a key field
df["region"] = df["region"].fillna("Unknown")
df["amount"] = df["amount"].fillna(df["amount"].median())

# Types
df["date"] = pd.to_datetime(df["date"], errors="coerce")
df["amount"] = pd.to_numeric(df["amount"], errors="coerce")

# Duplicates
print(df.duplicated().sum())
df = df.drop_duplicates()

# Text
df["region"] = df["region"].str.strip().str.title()

errors="coerce" turns anything unparseable into a missing value rather than raising. That is usually what you want on messy data — then count the resulting nulls to see how much failed.

The chained assignment warning#

Python
# May not modify df at all
df[df["amount"] > 100]["flag"] = True

# Correct
df.loc[df["amount"] > 100, "flag"] = True

The first version selects a subset, which may be a copy, and assigns to that copy. Pandas warns about it, and the warning is worth reading rather than suppressing. Use a single .loc with both the row condition and the column name.

Grouping and summarising#

Python
df.groupby("region")["amount"].sum()
df.groupby("region")["amount"].agg(["count", "mean", "median", "sum"])

df.groupby(["region", "product"])["amount"].mean().unstack()

# By month
df["month"] = df["date"].dt.to_period("M")
monthly = df.groupby("month")["amount"].sum()

# A pivot table
pd.pivot_table(df, values="amount", index="region",
               columns="product", aggfunc="sum", fill_value=0)

Group-and-aggregate is the single most useful pandas skill. A large share of real analysis is a variation on it.

New columns#

Python
df["with_vat"] = df["amount"] * 1.2

df["size"] = pd.cut(df["amount"], bins=[0, 50, 200, float("inf")],
                    labels=["small", "medium", "large"])

df["is_weekend"] = df["date"].dt.dayofweek >= 5

# Vectorised conditions - much faster than apply
import numpy as np
df["status"] = np.where(df["amount"] > 100, "high", "low")

Prefer vectorised operations to .apply() with a lambda. Apply runs a Python function per row and is often ten to a hundred times slower.

Plotting#

Python
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(9, 5))

monthly.plot(kind="bar", ax=ax, color="#2563eb")

ax.set_title("Monthly sales")
ax.set_xlabel("")
ax.set_ylabel("Total amount")
ax.spines[["top", "right"]].set_visible(False)

plt.tight_layout()
plt.savefig("monthly.png", dpi=150)
plt.show()

Removing the top and right spines and dropping a redundant axis label makes a chart considerably more readable for almost no effort.

A complete analysis#

Python
import pandas as pd
import matplotlib.pyplot as plt

# 1. Load
df = pd.read_csv("sales.csv", parse_dates=["date"])

# 2. Inspect
print(df.shape)
print(df.isna().sum())

# 3. Clean
df = df.dropna(subset=["amount", "date"])
df["region"] = df["region"].fillna("Unknown").str.strip().str.title()
df = df.drop_duplicates()

# 4. Explore
print(df["amount"].describe())
print(df["region"].value_counts())

# 5. Summarise
by_region = (df.groupby("region")["amount"]
               .agg(orders="count", total="sum", average="mean")
               .sort_values("total", ascending=False)
               .round(2))
print(by_region)

# 6. Plot
fig, ax = plt.subplots(figsize=(8, 5))
by_region["total"].plot(kind="barh", ax=ax, color="#2563eb")
ax.set_title("Total sales by region")
ax.set_xlabel("Amount")
ax.set_ylabel("")
plt.tight_layout()
plt.savefig("by_region.png", dpi=150)

# 7. Save
by_region.to_csv("summary.csv")

That shape — load, inspect, clean, explore, summarise, present — covers most analysis tasks. Steps 2 and 3 usually take longer than everything else combined.

Where scikit-learn comes in#

Python
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

X = df[["amount", "orders", "days_since_last"]]
y = df["churned"]

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

model = RandomForestClassifier(random_state=42).fit(X_train, y_train)
print(classification_report(y_test, model.predict(X_test)))

Modelling comes last, and only when there is a question a model answers. A clear summary table often answers the actual business question better than a model does.

Questions people ask#

Do I need Jupyter?

Not required, but well suited to exploration because you can run one cell at a time and see the output alongside the code. Move settled code into ordinary .py files.

pandas or SQL?

Both, usually. Do the filtering and aggregation in SQL where the data lives, then bring a smaller result into pandas for analysis and plotting.

Why is my pandas code slow?

Almost always .apply() or an explicit loop over rows. Look for a vectorised equivalent — arithmetic on whole columns, np.where, or a groupby.

What about polars?

A newer dataframe library that is considerably faster on large data and has a cleaner API. Worth knowing about; pandas remains the one with the most tutorials and the widest integration.

Where to go next#

Data visualization in Python, beyond the default chartRead next

Keep reading

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *