Why Python for data analysis, and how to set it up without getting lost

TL;DR

Difficulty: Beginner

A spreadsheet keeps the answer, a script keeps the method.

  • Move a task into Python when two of three are true: it will be done again, it combines exports, or someone else must check it. Move it regardless past 1,048,576 rows.
  • Opening an export in Excel changes it: 15 significant digits, lost leading zeros, text turned into dates.
  • Setup in June 2025: uv, one folder per project, pandas and JupyterLab, with the lock file committed.
  • Check rows, total and date range against the source first. In the example that alone corrected May's revenue by 4.2%.

Most people who ask whether they should learn Python are not unhappy with Excel. They are unhappy with the second time they build the same report. This chapter answers when a spreadsheet stops being enough, when it is still the right tool, and how to set up Python on your own laptop in under 20 minutes, ending with your first five lines of pandas on a real shaped shop export.

A spreadsheet keeps the answer, a script keeps the method

Most people who ask me whether they should learn Python are not unhappy with Excel. They are unhappy with the second time. The first monthly report was fine. The second one meant downloading the same five exports, deleting the same junk rows, fixing the same date column and rebuilding the same pivot table, from memory, slightly differently. By the sixth report nobody can say exactly which steps produced the number on slide three.

That is the real difference, and it is the idea this whole series rests on. A spreadsheet stores the result of your work. A script stores the work itself. Every filter, every join, every correction is written down as a line you can read, check, change and run again on next month's file in seconds. The question "where did this number come from?" stops being an archaeology project and becomes a matter of reading twenty lines from top to bottom.

So this first chapter is not a sales pitch for a programming language. It answers two plain questions: when does a spreadsheet stop being enough, and how do you set up Python on your own laptop without losing an afternoon to installers? By the end you will have a working setup, a project folder that a colleague could rebuild, and your first five lines of pandas reading a real shaped export.

Example: one invented shop and its analyst

Every chapter of this series uses the same invented business, so you can watch one analysis grow. Fernhill Home is an online homeware shop in York (fernhillhome.example) selling candles, ceramics and textiles. It has about 1,200 products and takes about 48,000 orders a year from about 21,000 customers, with an average order value of £58 and a gross margin of 52%. Grace founded it. Tariq is the analyst. Customers arrive through organic search, paid search, paid social, email, direct visits and referrals, and Fernhill runs Google Ads and Meta ads and sends a newsletter.

Tariq's standing question, the one Grace asks every month, is: "Which channel really pays back, and what should we do with next month's budget?" To answer it he needs five exports: the shop's order export, the Google Analytics 4 (GA4) data in BigQuery, the Google Ads report, the Meta Ads report and the newsletter tool's campaign report. Each has its own trap, and the series deals with every one. Today he takes the first step: one month of orders, read correctly, with three numbers checked before anything else.

If you only read one section

For the person who commissions analysis rather than writing it, here is the chapter in five points.

  • Python does not replace Excel. It replaces the repeated, invisible manual steps between a raw export and a trustworthy number. The final table can still land in a spreadsheet.
  • The trigger is repetition, combination and scrutiny, not size alone. If a task is repeated, joins two or more exports, or must be checked by someone else, it belongs in code. Size becomes a trigger when a file passes Excel's hard limit of 1,048,576 rows1, which one month of website events from a medium sized shop can do.
  • Opening an export in Excel is not neutral. Excel keeps 15 significant digits1, silently drops leading zeros and turns some text into dates. A script reads the file as it is.
  • The setup is a solved problem. In June 2025 the shortest sound path for one analyst is the tool uv, a project folder with its versions pinned, and JupyterLab or VS Code. It takes under 20 minutes.
  • It pays back over months, not days. In the example below a monthly report drops from about four hours to just over one, and the time spent learning and building pays back in about eight months. The bigger gain is that the number can be checked.

My view: if the same analysis lands on your desk every month, ask for it as a script plus its output, not as a spreadsheet. You are buying the method, and the method is what lets someone else check it, rerun it and still trust it in a year.

When a spreadsheet stops being enough

A spreadsheet is a superb tool for looking at a table and reasoning about it. Its limits show up in four places, and they are worth naming precisely, because "Excel cannot cope" is usually the wrong diagnosis.

The row limit is a hard wall

An Excel worksheet holds at most 1,048,576 rows by 16,384 columns1. That sounds huge until you meet event data. The GA4 export to BigQuery records every event, every page view, every scroll, every add to basket, and a single event can fill several rows once its nested parameters are unpacked2. A shop with a modest order count produces millions of events a month.

Rows beyond the limit simply cannot be in the sheet, and a limit like that is easy to miss. In October 2020 Public Health England reported that 15,841 positive COVID test results between 25 September and 2 October had been left out of the daily figures because some files "exceeded the maximum file size" the system could load3. A size limit in a data pipeline does not shout. It quietly hands you fewer rows than you sent.

Example: how far Fernhill's own data sits from the wall

Tariq sizes the data before choosing the tool. These figures are an illustration built on the example business, not measured data. Fernhill takes about 48,000 orders a year. With an average of 2.3 items per order, the order lines come to about 110,400 a year. Both fit easily in a sheet.

The website is another matter. With about 4,000 orders a month and a conversion rate around 2.1%, Fernhill sees roughly 190,000 sessions a month. If each session fires about 12 events, one month of GA4 events is 2,280,000 rows, more than twice the sheet limit. A quarter is 6,840,000.

Illustrative row counts for the example shop Fernhill Home. Orders per year 48,000. Order lines per year 110,400. Excel row limit 1,048,576. GA4 events per month 2,280,000. GA4 events per quarter 6,840,000. A single month of events is more than twice the sheet limit. Tap or click to enlarge

The orders are not the problem. The behaviour behind them is, and that is exactly the data that answers "which channel really pays back".

Manual steps nobody can repeat

The second limit is the one that costs most and shows least. Cleaning an export in a spreadsheet is a chain of clicks: filter, delete, paste values, find and replace, sort, a lookup in a helper column. None of it is recorded. The file that comes out looks the same whether the steps were done carefully or in a hurry before a meeting.

Example: the steps behind one number

Tariq writes down every step behind May's "revenue by channel" figure as he does it by hand. Download the order export. Open it. Delete the test orders, which he spots by the note column. Delete the staff orders. Decide what to do with refunds, which sit as separate rows with negative amounts. Convert the timestamps, which are in UTC. Build a pivot table by channel. Copy the totals into the report template. Check the total against the shop's admin screen. Notice a gap. Find a refund he missed. Fix it.

That is ten decisions, at least three of which (what counts as a test order, how refunds are netted, which time zone defines "May") change the answer. In a spreadsheet they live in Tariq's head. In a script they are lines that Grace, or Tariq's successor, can read.

Joins across exports

The third limit is combining files. Answering Grace's question means joining spend from Google Ads and Meta to orders and sessions, by date and by campaign. In a spreadsheet that is a chain of lookups that breaks as soon as a campaign is renamed or a date is formatted differently in one export. In pandas, a join is one line that states exactly which columns must match, and it can tell you how many rows found no partner. The chapter on joining and reshaping data takes this apart properly.

Models

The fourth limit is statistics beyond a trend line. Regression with several drivers, survival curves, a proper test of whether a difference is real: spreadsheets can do pieces of it, awkwardly, without a record. Python's statistical libraries do it with the method visible and the assumptions printed alongside the result.

Opening an export in a spreadsheet changes it

This is the trap tutorials rarely mention, and it catches careful people. Double clicking a CSV file feels like looking at it. It is not. The spreadsheet guesses a type for every column and converts the values, and when you save, the conversion is written back into the file.

Three conversions matter for marketing data.

  • Long numbers lose their last digits. Excel keeps 15 significant digits1. If a campaign or ad ID in an export is longer than that, it becomes a different number ending in zeros. Every join on that ID then fails or, worse, matches the wrong campaign.
  • Leading zeros disappear. An order number 0004101 becomes 4101, and no longer matches the shop's own records.
  • Text becomes dates. A study of genomics papers found that roughly one in five papers with supplementary Excel gene lists contained gene names that had been converted into dates or numbers4. Product codes and campaign names that look like dates suffer the same fate.

Example: the same ID, read two ways

Suppose Tariq's Meta report contains a campaign ID with 18 digits. Here is what happens to a long number stored as a floating point value, and what happens when you tell pandas to keep it as text. You can run this in any Python session.

import io
import pandas as pd

# One line of an ad report, exactly as it arrives
raw = "campaign_id,spend\n120212345678901234,10.50\n"

# Stored as a decimal number, the last digits are no longer exact
print(float("120212345678901234"))
# 1.2021234567890123e+17

# Read as text, the ID stays exactly as the platform wrote it
ads = pd.read_csv(io.StringIO(raw), dtype={"campaign_id": "string"})
print(ads["campaign_id"].iloc[0])
# 120212345678901234

The same applies to the order numbers. Without an instruction, pandas reads 0004101 as the integer 4101. With dtype={"order_id": "string"} it keeps the leading zeros. The habit that follows is simple and it is the first rule of the project folder below: raw exports go into a data/raw folder and are never opened and saved in a spreadsheet. Python reads them. If you want to look at one, look at the copy Python writes out.

The two of three rule: when to move a task into Python

Here is a check you can apply to any task in your week. It is my rule of thumb, and it has served better than arguing about tools in general.

Ask three questions about the task.

  1. Will it be done again? Monthly, weekly, or whenever new data arrives.
  2. Does it combine two or more exports? Orders with ad spend, sessions with newsletter sends.
  3. Must someone else be able to check it or run it? A manager who needs to trust it, a colleague who covers holidays, an auditor.

If two answers are yes, the task belongs in a script. If only one is yes, a spreadsheet is probably still the faster tool. One exception overrides the count: any file past the row limit goes to code regardless.

Example: Tariq sorts his week

TaskAgain?Two or more exports?Checked by others?Verdict
Monthly channel report for GraceYesYesYesPython
Weekly newsletter performanceYesNoYesPython
A one off price list for a wholesale enquiryNoNoNoSpreadsheet
Planning next month's budget split with GraceNoNoYesSpreadsheet, fed by the Python output
A year of GA4 events for a landing page questionNoNoNoPython, because of the row limit

The fourth row is the one people get wrong in both directions. The budget conversation is a discussion, and a spreadsheet is a good table to discuss around. But the numbers in it come out of the script, so the discussion starts from figures everyone can trace.

When Excel is still the right tool

I mean this seriously, because a series that only praises Python would not help you. A spreadsheet wins in several places.

  • One off questions on small tables. Opening a file, sorting a column and reading the answer takes a minute. Writing code for it takes longer.
  • Tables people edit by hand. A budget plan, a price list, a content calendar. These are inputs that humans type, not outputs computed from exports.
  • The last mile to a reader who lives in Excel. Python can write a tidy .xlsx file with the result, and the manager can filter it as usual.
  • Teams where nobody else codes. A script that only one person can run is its own risk. The earlier chapter on tools and workflow for good charts makes this point about chart making, and it holds for analysis too: the rerun cost decides, not taste.

Example: Grace's budget sheet stays a sheet

Grace keeps a budget sheet with one row per channel and her planned spend for the next three months. She changes it in meetings. Tariq does not move it to Python. He does the opposite: his script writes a small table of last month's cost and revenue per channel to outputs/channel_summary.xlsx, and Grace copies the five figures she needs into her sheet. The planning stays where Grace is fastest. The numbers come from the place where they can be checked.

What Python is, and what the PyData stack adds

Python is a general purpose programming language, first released in 1991, free and open source5. On its own it knows nothing special about tables. What makes it the default language for data analysis is a set of open source libraries, often called the PyData stack, that grew up around it. Wes McKinney's Python for Data Analysis (3rd edition, 2022), which he publishes free online, is the standard introduction to them and the reference book for this series5. I teach the ideas in my own words and on Fernhill's data, and point you to the matching chapter of the book where it helps.

LibraryWhat it does for an analystVersion in early June 2025
NumPyFast arrays of numbers and the maths on them. Almost everything else is built on it62.2.6
pandasTables (DataFrames) with named columns: reading files, cleaning, joining, grouping72.2.3
matplotlibThe base library for charts, with full control over every element83.10.3
seabornStatistical charts on top of matplotlib with good defaults0.13.2
statsmodelsClassical statistics and econometrics: regression with standard errors and tests90.14.4
scikit learnMachine learning: prediction, clustering, model evaluation101.6.1
JupyterLabThe browser based notebook environment for interactive work4.4.3

The version numbers are taken from each project's release history on the Python Package Index as of 4 June 202511. The Python language itself is at 3.13 (3.13.4 came out on 3 June 2025), and 3.14 is in beta with its final release planned for October12.

Two notes on versions, because they will matter in later chapters. McKinney's book uses Python 3.10 and the library versions of 2022. Where today's interface differs, I use today's and say so. And the pandas team has announced that pandas 3.0 will switch on "copy on write" by default and give text columns a dedicated string type7. That release has not happened as I write. When a chapter touches either behaviour, I point it out.

Example: which library answers which of Grace's questions

Grace's questionWhere Tariq does itLibrary
How much did each channel bring in last month?Read, clean and group the order exportpandas
Is paid social's return trending down?A weekly time series with a rolling averagepandas, then matplotlib
Does more Google Ads spend still bring more orders, or has it flattened?A regression of orders on spendstatsmodels
Which customers are likely to buy again?A prediction model on order historyscikit learn
How do I show it on one slide?A clean chart with one highlighted linematplotlib or seaborn

Each row is a later chapter. Today is the first row, and only its first half.

Why the interactive loop matters

Most programming languages are written, then run, then fixed. Data analysis does not work like that. You look at the data, notice something odd, look closer, change your mind about what to count, and look again. IPython, started by Fernando Pérez in 2001, was built for exactly this loop13. You type a line, see the result straight away, and decide the next line based on what you saw. McKinney calls it an "execute explore workflow"5. In 2014 the notebook part grew into Project Jupyter5, and a Jupyter notebook is now the standard way to work this way in a browser: cells of code, each with its output underneath, mixed with notes in plain text.

The loop is the reason analysts take to Python faster than they expect. It feels like a spreadsheet's immediacy with a record attached.

It also has a known weakness. In a notebook you can run cells in any order, change one in the middle and forget to rerun the ones below. The notebook then shows outputs that its own code no longer produces. A large study of 1,159,166 notebooks on GitHub managed to run only 24.11% of them without errors, and only 4.03% produced the same results as the ones saved in the file14.

Example: the rule Tariq follows before sending a number

Tariq has explored May's orders in a notebook for an hour, with cells run out of order. Before he copies a figure into Grace's report he uses Kernel, Restart Kernel and Run All Cells in JupyterLab. The notebook starts from nothing and runs top to bottom. If the figure is still the same, it is reproducible. If a cell fails, he has found a step that only worked because of something he did by hand earlier, and he fixes it now rather than next month. It takes ten seconds. I would make it a habit before any number leaves your screen.

Setup options compared, as of June 2025

Here is where most beginners lose an afternoon. There are several ways to install Python, and the internet's advice comes from different years. These are the options that matter in June 2025, compared fairly.

OptionWhat it isGood forWatch out for
python.org installer, venv and pipThe official Python, its built in tool for isolated environments, and its package installerUnderstanding the moving parts, environments where only standard tools are allowedSeveral manual steps, activation differs by system, pip does not pin versions unless you write them down
Anaconda or Miniconda with condaA distribution that brings Python and the scientific libraries together, with its own package managerTeams already standardised on it, packages with complicated system dependenciesAnaconda's terms require a paid plan for organisations with more than 200 employees or contractors15. The free conda forge channel avoids that for most uses
uvA fast package and project manager from Astral, first released in February 202416One person or a small team who want Python, the libraries and pinned versions with three commandsYounger than the others and still at version 0.7, so check its docs when something behaves unexpectedly
Jupyter Notebook and JupyterLabThe notebook environments, installed into your projectExploring data, explaining an analysis step by stepCells run out of order (see above)
VS CodeMicrosoft's free code editor, which opens notebooks and scripts side by sidePeople who will also write scripts and testsYou have to point it at the right Python environment (a "kernel")
Google ColabHosted notebooks in the browser, free with limits17Trying Python in five minutes with nothing installedRuns on Google's machines, sessions time out and the machine is deleted. Not the place for a customer export
Python in ExcelPython formulas inside a Microsoft 365 workbook, calculated in Microsoft's cloud18Small analyses that should stay in a workbookNeeds a qualifying subscription and internet access, and the workflow still lives in cells rather than in a script

A note on Colab and customer data. An order export with names, addresses or email addresses is personal data. Uploading it to any hosted service is a decision for whoever is responsible for data protection in the business, not something to do on a whim to try a tool. For learning, use the generated data in this series.

My view: what to choose

For a beginner working alone: uv, one folder per project, and JupyterLab. It installs Python for you, keeps each project's libraries separate, and writes down the exact versions in a lock file without you thinking about it. There is nothing to activate, which removes the most common first hour error on Windows.

For a small team: the same, plus the project folder in Git with pyproject.toml and uv.lock committed. A colleague clones the folder, runs one command, and has the identical environment. That is the whole point of the record.

If your company already supports Anaconda or conda: use what IT supports, with conda forge and one environment per project. McKinney's book walks through exactly that setup5. Fighting the company standard to save a few seconds on installs is not worth it.

The decision as a flow:

Tap or click to enlarge

The full setup, step by step

This is the setup Tariq uses, in the commands he types. It works on macOS, Linux and Windows. Everything happens in a terminal: Terminal on a Mac, PowerShell on Windows.

Example: Tariq sets up his laptop

Step 1: install uv. On macOS or Linux:

curl -LsSf https://astral.sh/uv/install.sh | sh

On Windows, in PowerShell:

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

Close the terminal and open a new one, so it picks up the new command. Check that it worked:

uv --version
# uv 0.7.10

Step 2: let uv install Python. You do not need Python installed first. uv downloads a standalone build and keeps it out of the way of any Python your system already has.

uv python install 3.13

Step 3: create the project folder. One folder per project, named after the question, not after the date.

uv init fernhill-analysis --python 3.13
cd fernhill-analysis

uv creates pyproject.toml (the project's description, including which libraries it needs), .python-version (which Python it uses), a README.md and a sample main.py. In a folder that is not yet in Git, it also starts a Git repository.

Step 4: add the libraries.

uv add pandas jupyterlab

This creates a virtual environment in .venv (a private copy of Python just for this project), installs pandas, NumPy as its dependency and JupyterLab into it, and writes uv.lock, which records the exact version of every package. On 4 June 2025 that resolves to pandas 2.2.3, NumPy 2.2.6 and JupyterLab 4.4.3. The pyproject.toml now contains:

dependencies = [
    "jupyterlab>=4.4.3",
    "pandas>=2.2.3",
]

Step 5: make the folders. Raw data in one place, never edited. Outputs in another.

mkdir -p data/raw outputs notebooks

On Windows PowerShell, mkdir data/raw, outputs, notebooks does the same.

Step 6: start JupyterLab.

uv run jupyter lab

uv run runs the command inside the project's environment, so the notebook sees exactly the libraries in uv.lock. A browser tab opens. Choose Python 3 under Notebook to create a notebook, and save it into notebooks. Since the notebook lives in notebooks, paths to data start with ../data/raw/. To keep the code below simple, I run it from the project folder itself, so the paths start with data/raw/.

If you prefer VS Code, open the folder with it, create a file ending in .ipynb, and when VS Code asks for a kernel choose the Python inside .venv. uv's documentation covers both routes19.

The project folder now looks like this:

fernhill-analysis/
  .python-version
  .venv/            # the environment: never edit, never commit, rebuild any time
  pyproject.toml    # what the project needs
  uv.lock           # exact versions of everything
  data/raw/         # exports exactly as downloaded, read only
  notebooks/        # exploration
  outputs/          # tables and charts the analysis produces

A colleague who receives this folder (without .venv and without the data) runs uv sync and has the same environment, down to the patch version. The Python documentation describes a virtual environment exactly that way: disposable, never committed, recreated from a list of requirements20.

If you use the python.org installer instead

The standard library route works too and is worth knowing, because you will meet it in every older tutorial. Install Python 3.13 from python.org (on Windows, tick the option to add Python to PATH21), then in the project folder:

python3 -m venv .venv
source .venv/bin/activate        # Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install pandas jupyterlab
python -m pip freeze > requirements.txt
jupyter lab

The difference is in the last but one line. With pip the exact versions are recorded only if you remember to write them down. With uv it happens on every uv add.

A first session: read the export and see the first rows

Now the real work. In a real project you would download the order export into data/raw. Here, so that you can run every line, the first cell builds a file with the same shape and the same traps as Fernhill's export: one month of orders in UTC, 12 test orders, 25 staff orders, and refunds as separate rows with negative amounts. The numbers come from a random generator with a fixed seed, so you get exactly the figures shown.

Example: build May's order export

from pathlib import Path

import numpy as np
import pandas as pd

rng = np.random.default_rng(2025)  # fixed seed: everyone gets the same data

n = 4_000  # real customer orders in May 2025
channels = ["organic search", "paid search", "paid social", "email", "direct", "referral"]
shares = [0.30, 0.24, 0.16, 0.12, 0.13, 0.05]
start = pd.Timestamp("2025-05-01", tz="UTC")
seconds_in_may = 31 * 24 * 60 * 60

orders = pd.DataFrame({
    "created_at_utc": start + pd.to_timedelta(rng.uniform(0, seconds_in_may, n), unit="s"),
    "channel": rng.choice(channels, size=n, p=shares),
    "total_gbp": rng.gamma(shape=4, scale=58 / 4, size=n).round(2),
    "kind": "order",
    "note": "",
})

# 12 test orders and 25 staff orders: real rows in the export, not real sales
extra = orders.sample(37, random_state=7).copy()
extra["note"] = ["test"] * 12 + ["staff"] * 25
orders = pd.concat([orders, extra], ignore_index=True)

# 140 refunds, each a separate row with a negative amount, three days later
refunded = orders[orders["note"] == ""].sample(140, random_state=11).copy()
refunded["kind"] = "refund"
refunded["total_gbp"] = -refunded["total_gbp"]
refunded["created_at_utc"] = refunded["created_at_utc"] + pd.Timedelta(days=3)
# refunds that fall in June belong to June's export
refunded = refunded[refunded["created_at_utc"] < start + pd.Timedelta(days=31)]
orders = pd.concat([orders, refunded], ignore_index=True)

# sort by time, number the rows like the shop does, write the CSV
orders = orders.sort_values("created_at_utc", ignore_index=True)
orders.insert(0, "order_id", [f"{i:07d}" for i in range(4_101, 4_101 + len(orders))])
orders["created_at_utc"] = orders["created_at_utc"].dt.strftime("%Y-%m-%d %H:%M:%S")

Path("data/raw").mkdir(parents=True, exist_ok=True)
orders.to_csv("data/raw/fernhill_orders_2025_05.csv", index=False)
print(len(orders))
# 4161

Do not worry about every line of that cell. It plays the part of the shop's download button, and the next chapters explain each tool it uses. From here on, everything is what you would write on real data.

Example: the first five lines of pandas

import pandas as pd

orders = pd.read_csv(
    "data/raw/fernhill_orders_2025_05.csv",
    dtype={"order_id": "string", "note": "string"},  # keep IDs exactly as text
    parse_dates=["created_at_utc"],                   # read timestamps as dates
)
orders.shape
# (4161, 6)

pd.read_csv reads the file into a DataFrame, pandas' word for a table with named columns. The two arguments are the habit from the section on spreadsheets: tell pandas which columns are text and which are dates instead of letting it guess22. orders.shape gives rows and columns: 4,161 rows, 6 columns.

orders.head()
order_idcreated_at_utcchanneltotal_gbpkindnote
000041012025-05-01 00:13:57organic search29.67order
100041022025-05-01 00:31:31paid social23.89order
200041032025-05-01 00:35:14email39.37order
300041042025-05-01 00:36:20paid search61.88order
400041052025-05-01 00:37:32paid search43.17order

head() shows the first five rows. The order IDs kept their leading zeros. An empty note shows as <NA>, pandas' marker for a missing value.

orders.dtypes
# order_id          string[python]
# created_at_utc    datetime64[ns]
# channel                   object
# total_gbp                float64
# kind                      object
# note              string[python]

dtypes lists each column's data type. The timestamp is a real date, the total is a decimal number, and the IDs are text. object is how pandas 2.2 stores text it was not told about. This is one of the defaults the announced pandas 3.0 will change.

orders["channel"].value_counts()
# organic search    1240
# paid search       1018
# paid social        652
# direct             545
# email              493
# referral           213

value_counts() counts how often each value appears. Five lines, and Tariq already knows the file's size, its columns, its types and where the orders came from.

Check three numbers before you trust any of them

Before any analysis, I check three numbers against the system the export came from: the row count, the total, and the date range. It takes two minutes and catches a truncated download, a wrong filter in the export screen, a time zone shift or a file from the wrong month before they reach a report. Then I look at the columns that decide what counts as a sale.

Example: Tariq reconciles May

len(orders)
# 4161

orders["total_gbp"].sum().round(2)
# 228006.15

orders["created_at_utc"].min(), orders["created_at_utc"].max()
# (Timestamp('2025-05-01 00:13:57'), Timestamp('2025-05-31 23:04:58'))

The shop's admin screen for May shows 4,161 transactions and net sales of £228,006.15. The first two numbers match. The date range runs from the first to the last day of May, in UTC. That last detail matters: York is on British Summer Time in May, one hour ahead of UTC, so an order at 11.30pm UTC on 31 May was placed at 12.30am on 1 June in Fernhill's own time. For a monthly total the shift is small. For a daily chart it moves orders between days, and the chapter on time series handles it properly.

Now the columns that define a sale:

orders["kind"].value_counts()
# order     4037
# refund     124

orders["note"].value_counts()
# staff    25
# test     12

124 refunds fell inside May (the other 16 fall in June and belong to June's export). 12 test orders and 25 staff orders sit among the real ones.

Example: the first answer, and why the obvious one is wrong

Here is revenue by channel computed two ways. The first is what a pivot table on the raw export gives you if you sum the order rows: test and staff orders included, refunds ignored. The second keeps only real customer rows, so the refunds are netted off.

# the obvious way: sum the order rows
naive = orders[orders["kind"] == "order"].groupby("channel")["total_gbp"].sum()

# real customer activity only: no test or staff rows, refunds netted off
real = orders[orders["note"].isna()]
clean = real.groupby("channel")["total_gbp"].sum()

summary = pd.DataFrame({"naive_gbp": naive, "clean_gbp": clean}).round(0)
summary["difference_gbp"] = summary["naive_gbp"] - summary["clean_gbp"]
summary.sort_values("clean_gbp", ascending=False)
channelnaive_gbpclean_gbpdifference_gbp
organic search70,04867,1062,942
paid search57,04254,7262,316
paid social36,96735,4491,518
direct30,70929,2761,433
email27,84226,940902
referral12,78912,380409
Total235,397225,8779,520

The obvious number overstates May by £9,520, or 4.2% on top of the true £225,877. It is made of £7,391 of refunds and £2,129 of test and staff orders. Paid social looks £1,518 better than it was, and paid search £2,316, exactly the channels whose budgets Grace wants to discuss. A 4% error is invisible to the eye and large enough to change a budget decision.

The point is not that Python got the right answer. Tariq got it, by deciding what counts as a sale. The point is that the decision is now the line orders[orders["note"].isna()], visible to Grace and rerun automatically next month. The chapter on cleaning data turns these choices into a proper, tested cleaning step.

The errors you will meet in the first hour

Every beginner meets the same handful of errors. None of them means you have done something stupid. Most of them mean that two pieces of software disagree about where something is.

What you seeWhat it meansThe fix
uv: command not found or 'uv' is not recognizedThe terminal was open before uv was installed and does not know the new commandClose the terminal and open a new one
ModuleNotFoundError: No module named 'pandas'The code runs in a different Python from the one you installed pandas intoStart JupyterLab with uv run jupyter lab from the project folder, or choose the .venv kernel in VS Code
error: externally-managed-environment from pipYour system's Python (for example from Homebrew or Linux) refuses packages outside a virtual environment, by design23Use a project environment (uv, or venv) instead of installing globally
Activate.ps1 cannot be loaded because running scripts is disabledWindows PowerShell blocks the venv activation scriptUse uv, which needs no activation, or follow the execution policy step in the venv documentation20
FileNotFoundError: ... fernhill_orders_2025_05.csvThe path is relative to where the notebook runs, not where the file isCheck the folder with from pathlib import Path; Path.cwd() and adjust the path, for example ../data/raw/... from notebooks
UnicodeDecodeError: 'utf-8' codec can't decode byteThe file is not in UTF 8, often an older export in Latin 1 or Windows encodingPass encoding="latin-1" or encoding="cp1252" to read_csv
Everything lands in one columnThe file uses semicolons, not commas, between fieldsPass sep=";", and for European number formats decimal="," and thousands="."
Order numbers without leading zeros, IDs ending in 000pandas or a spreadsheet guessed a number typedtype={"order_id": "string"}, and never save a raw export from a spreadsheet
A figure changes after "Run All"Cells were run out of orderRestart and run all before you trust a number

Example: the wrong Python, step by step

Tariq installs pandas, opens a notebook from the Start menu shortcut an old installation left behind, types import pandas as pd and gets ModuleNotFoundError. pandas is installed, just not in the Python that notebook uses. He checks which Python runs his code:

import sys
sys.executable
# '/Applications/OldPython/bin/python3'   (not the project's .venv)

The fix is to start JupyterLab from the project, so the notebook runs inside .venv:

cd fernhill-analysis
uv run jupyter lab

Now sys.executable ends in fernhill-analysis/.venv/bin/python3 (on Windows fernhill-analysis\.venv\Scripts\python.exe) and the import works. Checking sys.executable is the fastest way to solve nearly every "but I installed it" problem.

Does it pay back? The time a monthly report takes

The honest answer depends on how often you repeat the work, so it is worth calculating rather than asserting. The figures below are an illustration for the example business, not a measurement: Tariq times one month's report by hand and estimates the same report as a script.

Example: Tariq times his monthly report

Illustrative minutes per step for the example shop's monthly channel report. Download five exports: 25 by hand, 25 with a script. Clean and paste: 75 by hand, 0 with a script. Match orders to channels and spend: 50 by hand, 0 with a script. Pivot tables and charts: 45 by hand, 0 with a script. Run the script: 0 by hand, 3 with a script. Check and reconcile: 25 by hand, 15 with a script. Write the commentary: 30 in both. Total 250 minutes by hand, 73 with a script. Tap or click to enlarge

By hand the report takes 250 minutes. As a script it takes 73: the downloads and the commentary stay, the cleaning, matching and charting run in three minutes, and the checks are quicker because the script prints the three numbers itself. The saving is 177 minutes, about 2.95 hours a month.

The script is not free. Tariq estimates 24 hours to learn enough Python and write the first version. When does that pay back? The break even month is the one off cost divided by the saving per month (Foundations: ratios and rates):

m∗=Cthand−tscriptm^{*} = \frac{C}{t_{\text{hand}} - t_{\text{script}}}

where m∗m^{*} is the number of months until the time saved equals the time invested, CC is the one off cost in hours, thandt_{\text{hand}} is the hours per report by hand and tscriptt_{\text{script}} is the hours per report with the script.

With Tariq's figures, C=24C = 24, thand=250/60=4.17t_{\text{hand}} = 250/60 = 4.17 and tscript=73/60=1.22t_{\text{script}} = 73/60 = 1.22:

m∗=244.17−1.22=242.95=8.1m^{*} = \frac{24}{4.17 - 1.22} = \frac{24}{2.95} = 8.1

Here m∗=8.1m^{*} = 8.1 months, so the script pays back in a little over eight months of monthly reports, faster if a weekly report uses the same code, and the second script costs far less than 24 hours because the learning is done.

My view: the payback calculation undersells it. The larger return is the 4.2% error from the previous section, found once and never made again, and a report that someone else can run during Tariq's holiday. Those do not show up in minutes, but they are what Grace is really paying for.

What comes next in this series

This chapter set up the tools and read one file. The next chapter covers just enough of the Python language for analysis: values, lists, dictionaries, loops and functions, explained through Fernhill's data. After that come NumPy and why arrays are fast, pandas Series and DataFrames in depth, loading the other four exports (including the GA4 data from BigQuery, whose setup the guide to BigQuery for eCommerce analytics describes), cleaning, joining, grouping, time series, charts, statistical models and finally a workflow with tests. When charts arrive, they build on the data storytelling series, starting with why the story starts before the chart and exploring data with charts before you present anything.

If you want this kind of analysis built for your own shop rather than learning it yourself, that is part of my data science work: reports and dashboards built as code, in your accounts, which you own.

Conclusion

A spreadsheet is the right tool for looking and the wrong tool for repeating. Move a task into Python when two of three things are true: it will be done again, it combines exports, or someone else must check it. Move it regardless when the data passes 1,048,576 rows. Keep raw exports away from spreadsheets, because opening and saving them changes the data. Set up with uv, one folder per project, pandas and JupyterLab, and commit the lock file. Read every export with its types stated, then check three numbers against the source before you believe anything. In Fernhill's case that check alone moved May's revenue by 4.2%, and it will run itself every month from now on.

If you would like your monthly channel report rebuilt as a script that checks itself, book the free workshop: we look at your exports together and decide what belongs in code, and the first two weeks of work are on me.

Sources

  1. 1.
  2. 2.

    Google Analytics Help, BigQuery Export schema, https://support.google.com/analytics/answer/7029846

  3. 3.

    Public Health England, PHE statement on delayed reporting of COVID-19 cases, GOV.UK, 4 October 2020, https://www.gov.uk/government/news/phe-statement-on-delayed-reporting-of-covid-19-cases

  4. 4.

    Mark Ziemann, Yotam Eren and Assam El-Osta, Gene name errors are widespread in the scientific literature, Genome Biology 17, 177, 2016, https://doi.org/10.1186/s13059-016-1044-7

  5. 5.

    Wes McKinney, Python for Data Analysis, 3rd edition, O'Reilly, 2022, chapter 1: Preliminaries, open access edition, https://wesmckinney.com/book/preliminaries.html

  6. 6.

    Charles R. Harris and others, Array programming with NumPy, Nature 585, 357 to 362, 2020, https://doi.org/10.1038/s41586-020-2649-2

  7. 7.

    pandas development team, What's new in 2.2.0 (January 19, 2024), section Upcoming changes in pandas 3.0, https://pandas.pydata.org/pandas-docs/version/2.2/whatsnew/v2.2.0.html

  8. 8.

    John D. Hunter, Matplotlib: a 2D graphics environment, Computing in Science and Engineering 9(3), 90 to 95, 2007, https://doi.org/10.1109/MCSE.2007.55

  9. 9.

    statsmodels developers, statsmodels 0.14.4 documentation, https://www.statsmodels.org/v0.14.4/

  10. 10.

    Fabian Pedregosa and others, Scikit-learn: machine learning in Python, Journal of Machine Learning Research 12, 2825 to 2830, 2011, https://jmlr.org/papers/v12/pedregosa11a.html

  11. 11.

    Python Package Index, release histories of pandas, NumPy, matplotlib, seaborn, statsmodels, scikit-learn and JupyterLab, checked for releases up to 4 June 2025, https://pypi.org/project/pandas/#history

  12. 12.

    Python Software Foundation, Python 3.13.4 release page, 3 June 2025, https://www.python.org/downloads/release/python-3134/, and PEP 745, Python 3.14 release schedule, https://peps.python.org/pep-0745/

  13. 13.

    Fernando Pérez and Brian E. Granger, IPython: a system for interactive scientific computing, Computing in Science and Engineering 9(3), 21 to 29, 2007, https://doi.org/10.1109/MCSE.2007.53

  14. 14.

    João Felipe Pimentel, Leonardo Murta, Vanessa Braganholo and Juliana Freire, A large scale study about quality and reproducibility of Jupyter notebooks, 2019 IEEE/ACM 16th International Conference on Mining Software Repositories, 507 to 517, 2019, https://doi.org/10.1109/MSR.2019.00077

  15. 15.

    Anaconda, Terms of Service, section 1, version archived on 30 May 2025, https://web.archive.org/web/20250530205635/https://www.anaconda.com/legal/terms/terms-of-service

  16. 16.

    Charlie Marsh, uv: Python packaging in Rust, Astral blog, 15 February 2024, https://astral.sh/blog/uv

  17. 17.

    Google, Colaboratory frequently asked questions, https://research.google.com/colaboratory/faq.html

  18. 18.
  19. 19.

    Astral, uv documentation, Using uv with Jupyter, https://docs.astral.sh/uv/guides/integration/jupyter/

  20. 20.

    Python documentation 3.13, venv: creation of virtual environments, https://docs.python.org/3.13/library/venv.html

  21. 21.

    Python documentation 3.13, Using Python on Windows, https://docs.python.org/3.13/using/windows.html

  22. 22.
  23. 23.

    Python Enhancement Proposals, PEP 668: Marking Python base environments as externally managed, 2021, https://peps.python.org/pep-0668/

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.

Donate to Shelter