Python Data Science: NumPy, Pandas, and Plotting
A data science script is rarely one clever formula. It is a chain of small, repeatable steps: pull raw numbers into memory, check what shape they are, repair the rows that are broken, slice out the part you care about, summarise it, and finally draw a picture that someone else can act on. NumPy and pandas each own a piece of that chain, and knowing where one should stop and the other start saves you from the most common beginner mistake â writing Python loops over data that a native routine already handles.
By the end of this lesson you should be able to: build and manipulate n-dimensional arrays without explicit loops, load a tabular dataset and profile it in three calls, filter and group rows on multiple conditions, decide how to treat missing values, and turn a summary table into a chart you can defend in a review.
Where NumPy ends and pandas begins
NumPy gives you a contiguous block of typed numbers plus an algebra over it. pandas gives you labelled rows and columns, missing-value semantics, and group logic on top of that same block. The practical dividing line is simple: anything that is a matrix, signal, image tensor, or feature column belongs in NumPy; anything that is a record â an order, a patient visit, a sensor reading with a timestamp and a device id â belongs in a DataFrame.
import numpy as np
import pandas as pd
temperatures = np.array([21.4, 22.9, 19.8, 24.1, np.nan])
readings = pd.DataFrame({
"sensor": ["a1", "a1", "a2", "a2", "a1"],
"hour": [0, 6, 0, 6, 12],
"temp": [21.4, 22.9, 19.8, 24.1, np.nan],
})
print(temperatures.mean()) # nan â NumPy has no skip-na default
print(readings["temp"].mean()) # 22.05 â pandas skips missing by default
That single difference in default behaviour is responsible for an enormous number of wrong numbers in production reports, and it is the first thing to check whenever a summary looks implausible.
A useful habit is to keep one variable for the raw column and one for the cleaned version, so that a suspicious result can be traced back instead of guessed at. NumPy arrays are also strongly typed: an array of integers will silently reject or upcast values depending on how you assign them, which is a feature when your data is genuinely integral and a trap when a column of identifiers was read as floats and lost their leading zero.
Vectorised arithmetic replaces loops
The reason NumPy exists at all is that a loop written in Python interpreter code is
orders of magnitude slower than a loop written in C and executed over a contiguous
buffer. When you write array * 2, no Python-level iteration happens; the multiply runs
element by element inside the compiled runtime and returns a new array.
sales = np.array([1200.0, 950.0, 1430.0, 780.0, 1610.0])
costs = np.array([700.0, 610.0, 890.0, 500.0, 940.0])
margin = (sales - costs) / sales # vector of margins
print(np.round(margin * 100, 1)) # [41.7 35.8 37.8 35.9 41.6]
print(margin.mean(), margin.max()) # 0.3855 0.4166
print(np.where(margin > 0.4, "healthy", "watch"))
# ['healthy' 'watch' 'watch' 'watch' 'healthy']
Boolean masks compose the same way. margin > 0.4 produces an array of True and
False, and indexing with it keeps only the matching entries, so selection, arithmetic
and reduction all chain without a single for.
Choosing between arrays and lists
| Operation | Python list | NumPy array | Why it matters |
|---|---|---|---|
x * 2 | Repeats the whole list | Doubles every element | Arithmetic on lists silently does the wrong thing |
| Adding 1 to 10âļ items | Interpreter loop, seconds | Contained C loop, milliseconds | Batch jobs stay interactive |
| Memory per 10âļ ints | ~28 MB of objects | 4 or 8 MB typed block | Fits in cache, feeds SIMD |
| Missing values | No built-in | np.nan plus nanmean | Explicit handling of gaps |
| Slicing | Copies a new list | Returns a view | Views avoid needless copies |
The list column is not a criticism â lists are the right container for heterogeneous records and for building up unknown sequences. The point is that numeric work should be pushed into arrays as early as possible, and pulled out to Python objects only at the very end when you hand results to a person or a library.
Loading data and profiling it before trusting it
Three calls tell you most of what you need to know about a fresh file: head to see the
raw shape of a row, info to see types and null counts, and describe to see the
distribution of every numeric column. Doing this before any analysis prevents the classic
failure where an identifier column is averaged, or a date column loaded as text silently
sorts lexicographically.
orders = pd.read_csv("orders.csv", parse_dates=["placed_at"])
print(orders.head(3))
print(orders.dtypes)
print(orders.describe(include="all"))
print(orders["channel"].value_counts(normalize=True).round(3))
print(orders["placed_at"].min(), orders["placed_at"].max())
Read channel as a proportion rather than a count when you want to know whether a
segment is a real business line or a rounding error in your funnel, and always check the
date range so you know whether you are looking at last week or the last three years.
Filtering, grouping, and aggregation
Most business questions are group-by questions: revenue per channel, error rate per service, median latency per region. pandas expresses them as a chain â filter the rows you are entitled to consider, group by the dimension, aggregate the measure â and the chain reads like the sentence you would say out loud.
valid = orders[orders["status"] != "cancelled"]
valid = valid[valid["total"] > 0]
summary = (
valid.groupby("channel")
.agg(
orders=("total", "size"),
revenue=("total", "sum"),
average=("total", "mean"),
unique_customers=("customer_id", "nunique"),
)
.sort_values("revenue", ascending=False)
)
summary["revenue_share"] = (summary["revenue"] / summary["revenue"].sum()).round(3)
print(summary)
Two details in that block are worth pausing on. size counts rows including those with a
missing measure, while count would exclude them â so orders and average can disagree
about how many observations they came from. And nunique rather than n_distinct on a
per-group basis tells you whether a channel's revenue comes from many buyers or a handful
of whales.
Missing data changes the conclusion, not just the number
Dropping nulls is a decision about scope, not a formatting chore. If 40 % of a column is null because the field was only introduced in a later release, deleting those rows silently truncates your history and biases every trend you draw afterwards.
gaps = orders.isna().sum()
print(gaps[gaps > 0])
orders["discount"] = orders["discount"].fillna(0.0)
orders["placed_at"] = orders["placed_at"].fillna(orders["placed_at"].min())
# keep partial rows, but record how incomplete each one is
orders["missing_fields"] = orders.isna().sum(axis=1)
print(orders[orders["missing_fields"] > 0].head())
Fill, drop, or flag â in that order of preference, and only after you know why the value is missing. A flag column costs one integer per row and buys you the ability to revisit the decision later without reloading the file.
Charting the answer you actually computed
A chart is the last step, never the first. Plotting a raw column before grouping invites you to spot patterns in noise; plotting the grouped table shows the comparison your reader needs. Keep the axis labels attached to the units you computed, and resist the temptation to decorate â a bar chart with five categories needs no gradient.
import matplotlib.pyplot as plt
plot_df = summary.reset_index()
fig, ax = plt.subplots(figsize=(7, 4))
bars = ax.bar(plot_df["channel"], plot_df["revenue"], color="#2563eb")
ax.set_ylabel("Revenue (USD)")
ax.set_title("Revenue by acquisition channel")
ax.bar_label(bars, fmt="$%.0f", padding=3)
fig.tight_layout()
plt.show()
If the chart and the table disagree, the bug is in the chart â go back to the grouped frame, confirm the numbers, and only then adjust the visual.
One last habit separates a disposable notebook from an analysis you can rerun: write the whole chain as a single script with the load step at the top, so that a refreshed export reproduces every number and every figure without manual clicking. When a stakeholder asks how a figure changed since yesterday, the answer should be one command, not a search through cell history.
Common Mistakes
Averaging a column that contains nulls and getting NaN back
Fix: Check isna().sum() first, then choose fillna, dropna, or a nan-aware aggregator such as nanmean
Looping over DataFrame rows with iterrows to compute a metric
Fix: Express the metric with vectorised methods or groupby().agg() so the work runs in compiled code
Reading a CSV without specifying dtypes or date parsing
Fix: Pass parse_dates and useful dtypes at read time so sorting and filtering behave as expected
Plotting before grouping, then reading structure out of noise
Fix: Aggregate to the exact comparison you want, then chart that table
Best Practices
- Profile with head, info, describe, and value_counts before writing any transformation logic
- Keep raw data immutable: build cleaned frames as new variables so you can always re-derive them
- Name intermediate frames after what they mean (valid_orders, not df2) â the chain should read like a sentence
- Record the units and currency of every measure in a comment next to the column definition
Key Takeaways
- NumPy owns numeric arrays and vectorised arithmetic; pandas owns labelled tables, nulls, and grouping
- pandas skips missing values by default while NumPy does not â check this before trusting any average
- Filter, group, aggregate, then chart: the order of operations is the analysis
- size counts rows and count counts non-null values; they answer different questions
- Always profile a fresh dataset with head, info, and describe before transforming it