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 an Irish shop's order 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. Ardmore Home is an online homeware shop in Sligo (ardmorehome.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 €66 and a gross margin of 52%. Áine founded it. Darragh is the analyst. Customers arrive through organic search, paid search, paid social, email, direct visits and referrals, and Ardmore runs Google Ads and Meta ads and sends a newsletter.
Darragh's standing question, the one Áine 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 Ardmore's own data sits from the wall
Darragh sizes the data before choosing the tool. These figures are an illustration built on the example business, not measured data. Ardmore 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%, Ardmore 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.
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
Darragh 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 Darragh's head. In a script they are lines that Áine, or Darragh's successor, can read.
Joins across exports
The third limit is combining files. Answering Áine'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
0004101becomes4101, 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 Darragh'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.
- Will it be done again? Monthly, weekly, or whenever new data arrives.
- Does it combine two or more exports? Orders with ad spend, sessions with newsletter sends.
- 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: Darragh sorts his week
| Task | Again? | Two or more exports? | Checked by others? | Verdict |
|---|---|---|---|---|
| Monthly channel report for Áine | Yes | Yes | Yes | Python |
| Weekly newsletter performance | Yes | No | Yes | Python |
| A one off price list for a wholesale enquiry | No | No | No | Spreadsheet |
| Planning next month's budget split with Áine | No | No | Yes | Spreadsheet, fed by the Python output |
| A year of GA4 events for a landing page question | No | No | No | Python, 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 still wins in a good few 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
.xlsxfile 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: Áine's budget sheet stays a sheet
Áine keeps a budget sheet with one row per channel and her planned spend for the next three months. She changes it in meetings. Darragh 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 Áine copies the five figures she needs into her sheet. The planning stays where Áine 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 Ardmore's data, and point you to the matching chapter of the book where it helps.
| Library | What it does for an analyst | Version in early June 2025 |
|---|---|---|
| NumPy | Fast arrays of numbers and the maths on them. Almost everything else is built on it6 | 2.2.6 |
| pandas | Tables (DataFrames) with named columns: reading files, cleaning, joining, grouping7 | 2.2.3 |
| matplotlib | The base library for charts, with full control over every element8 | 3.10.3 |
| seaborn | Statistical charts on top of matplotlib with good defaults | 0.13.2 |
| statsmodels | Classical statistics and econometrics: regression with standard errors and tests9 | 0.14.4 |
| scikit learn | Machine learning: prediction, clustering, model evaluation10 | 1.6.1 |
| JupyterLab | The browser based notebook environment for interactive work | 4.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 Áine's questions
| Áine's question | Where Darragh does it | Library |
|---|---|---|
| How much did each channel bring in last month? | Read, clean and group the order export | pandas |
| Is paid social's return trending down? | A weekly time series with a rolling average | pandas, then matplotlib |
| Does more Google Ads spend still bring more orders, or has it flattened? | A regression of orders on spend | statsmodels |
| Which customers are likely to buy again? | A prediction model on order history | scikit learn |
| How do I show it on one slide? | A clean chart with one highlighted line | matplotlib 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 Darragh follows before sending a number
Darragh has explored May's orders in a notebook for an hour, with cells run out of order. Before he copies a figure into Áine'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.
| Option | What it is | Good for | Watch out for |
|---|---|---|---|
python.org installer, venv and pip | The official Python, its built in tool for isolated environments, and its package installer | Understanding the moving parts, environments where only standard tools are allowed | Several manual steps, activation differs by system, pip does not pin versions unless you write them down |
Anaconda or Miniconda with conda | A distribution that brings Python and the scientific libraries together, with its own package manager | Teams already standardised on it, packages with complicated system dependencies | Anaconda'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 |
| uv | A fast package and project manager from Astral, first released in February 202416 | One person or a small team who want Python, the libraries and pinned versions with three commands | Younger than the others and still at version 0.7, so check its docs when something behaves unexpectedly |
| Jupyter Notebook and JupyterLab | The notebook environments, installed into your project | Exploring data, explaining an analysis step by step | Cells run out of order (see above) |
| VS Code | Microsoft's free code editor, which opens notebooks and scripts side by side | People who will also write scripts and tests | You have to point it at the right Python environment (a "kernel") |
| Google Colab | Hosted notebooks in the browser, free with limits17 | Trying Python in five minutes with nothing installed | Runs on Google's machines, sessions time out and the machine is deleted. Not the place for a customer export |
| Python in Excel | Python formulas inside a Microsoft 365 workbook, calculated in Microsoft's cloud18 | Small analyses that should stay in a workbook | Needs 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:
The full setup, step by step
This is the setup Darragh 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: Darragh 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 ardmore-analysis --python 3.13
cd ardmore-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:
ardmore-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 in Cork or Galway 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 Ardmore'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_eur": rng.gamma(shape=4, scale=66 / 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_eur"] = -refunded["total_eur"]
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/ardmore_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/ardmore_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_id | created_at_utc | channel | total_eur | kind | note | |
|---|---|---|---|---|---|---|
| 0 | 0004101 | 2025-05-01 00:13:57 | organic search | 33.76 | order | |
| 1 | 0004102 | 2025-05-01 00:31:31 | paid social | 27.19 | order | |
| 2 | 0004103 | 2025-05-01 00:35:14 | 44.80 | order | ||
| 3 | 0004104 | 2025-05-01 00:36:20 | paid search | 70.42 | order | |
| 4 | 0004105 | 2025-05-01 00:37:32 | paid search | 49.12 | order |
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_eur 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 Darragh 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: Darragh reconciles May
len(orders)
# 4161
orders["total_eur"].sum().round(2)
# 259455.49
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 €259,455.49. The first two numbers match. The date range runs from the first to the last day of May, in UTC. That last detail matters: Sligo is on Irish Standard 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 Ardmore's own time. For a monthly total the shift hardly matters. 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_eur"].sum()
# real customer activity only: no test or staff rows, refunds netted off
real = orders[orders["note"].isna()]
clean = real.groupby("channel")["total_eur"].sum()
summary = pd.DataFrame({"naive_eur": naive, "clean_eur": clean}).round(0)
summary["difference_eur"] = summary["naive_eur"] - summary["clean_eur"]
summary.sort_values("clean_eur", ascending=False)
| channel | naive_eur | clean_eur | difference_eur |
|---|---|---|---|
| organic search | 79,710 | 76,362 | 3,348 |
| paid search | 64,910 | 62,275 | 2,635 |
| paid social | 42,066 | 40,338 | 1,728 |
| direct | 34,945 | 33,314 | 1,631 |
| 31,682 | 30,656 | 1,026 | |
| referral | 14,553 | 14,088 | 465 |
| Total | 267,866 | 257,033 | 10,833 |
The obvious number overstates May by €10,833, or 4.2% on top of the true €257,033. It is made of €8,410 of refunds and €2,423 of test and staff orders. Paid social looks €1,728 better than it was, and paid search €2,635, exactly the channels whose budgets Áine 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. Darragh 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 Áine 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 see | What it means | The fix |
|---|---|---|
uv: command not found or 'uv' is not recognized | The terminal was open before uv was installed and does not know the new command | Close 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 into | Start JupyterLab with uv run jupyter lab from the project folder, or choose the .venv kernel in VS Code |
error: externally-managed-environment from pip | Your system's Python (for example from Homebrew or Linux) refuses packages outside a virtual environment, by design23 | Use a project environment (uv, or venv) instead of installing globally |
Activate.ps1 cannot be loaded because running scripts is disabled | Windows PowerShell blocks the venv activation script | Use uv, which needs no activation, or follow the execution policy step in the venv documentation20 |
FileNotFoundError: ... ardmore_orders_2025_05.csv | The path is relative to where the notebook runs, not where the file is | Check 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 byte | The file is not in UTF 8, often an older export in Latin 1 or Windows encoding | Pass encoding="latin-1" or encoding="cp1252" to read_csv |
| Everything lands in one column | The file uses semicolons, not commas, between fields | Pass sep=";", and for European number formats decimal="," and thousands="." |
| Order numbers without leading zeros, IDs ending in 000 | pandas or a spreadsheet guessed a number type | dtype={"order_id": "string"}, and never save a raw export from a spreadsheet |
| A figure changes after "Run All" | Cells were run out of order | Restart and run all before you trust a number |
Example: the wrong Python, step by step
Darragh 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 ardmore-analysis
uv run jupyter lab
Now sys.executable ends in ardmore-analysis/.venv/bin/python3 (on Windows ardmore-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: Darragh times one month's report by hand and estimates the same report as a script.
Example: Darragh times his monthly report
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. Darragh 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):
where is the number of months until the time saved equals the time invested, is the one off cost in hours, is the hours per report by hand and is the hours per report with the script.
With Darragh's figures, , and :
Here 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 Darragh's holiday. Those do not show up in minutes, but they are what Áine 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 Ardmore'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 Ardmore's case that check alone moved May's revenue by 4.2%, and it will run itself every month from now on.
