Python basics for analysts: the language you actually need
TL;DR
Difficulty: Beginner
An analyst needs a small slice of Python, learned well, and can skip classes, decorators and async for now.
- The slice: five value types, four containers (list, tuple, dict, set), slicing, comprehensions, functions, f strings, loops, tracebacks, imports, pathlib and datetime.
- A cleaning rule is a business decision: put it in a dictionary people can read and sign off, and stop the run on any unknown value.
- Money goes in whole pence or Decimal, never raw floats. Every time gets its time zone, or sales move month.
- In the example, 14 raw campaign names become four campaigns, and the summer sale turns out to be £4,486.75, almost half of May's paid media.
What to read first
Python is a big language, and most of it was built for people writing software. An analyst needs a small slice of it, learned properly. This chapter names that slice, teaches every part with runnable code on an invented homeware shop's data, and ends by cleaning the campaign names that stand between the shop and an honest answer about its ad spend.
If you only read one section
Python is a big language, and most of it was built for people writing software. An analyst needs a small, specific slice of it: enough to hold values, give them names, repeat a step, and turn a rule into something you can run again next month. Everything else can wait, and much of it can wait for years.
This chapter is that slice. It follows Fernhill Home, an invented online homeware shop in York that sells candles, ceramics and textiles, runs Google Ads and Meta ads and sends a newsletter. Grace founded it. Tariq is the analyst, and his standing question is the one every shop owner asks: which channel really pays back, and where should next month's budget go? Before he can answer it, he has to make the data agree with itself. The first thing that disagrees is the campaign names.
Here is the idea I would put above everything else in this chapter: a cleaning rule is a business decision, so write it where people can read it. When Tariq decides that fb_summer, Summer_Sale and summer-sale are all the same campaign, that is a decision about money. In a spreadsheet it disappears into a filter, a find and replace, or a formula in a cell nobody opens. In Python it becomes a small dictionary of a few lines that Grace can read, question and approve, and that runs identically on next month's export. The language features in this chapter are the ones that make that possible.
For the person who commissions this work. If you pay for analysis rather than doing it, you do not need to read the code. Ask for four things and you will get most of the benefit:
- The cleaning rules as a readable list ("these raw names count as this campaign"), not buried in the code.
- A check that stops the run when a new, unknown value appears, instead of quietly lumping it in somewhere.
- Money stored as whole pence (or handled with a decimal type), so totals reconcile to the penny with the ad platforms' invoices.
- Every date and time stated with its time zone, so a sale at half past midnight lands in the right day and the right month.
In the worked example below, cleaning 14 raw campaign names down to four real campaigns changes the picture completely: the biggest campaign by raw name shows £1,820, while the real summer sale spent £4,486.75, almost half of the month's paid media.
My view: learn the small slice properly, skip the rest without guilt, and move to pandas as soon as you can. Most of the Python an analyst writes is short, and the value is not in clever code. It is in rules that are visible, checks that fail loudly, and numbers that add up.
The analyst's slice of Python
Python's official tutorial runs to 16 chapters and covers classes, modules, the standard library, virtual environments and more1. Wes McKinney's Python for Data Analysis, the standard book on pandas, spends two chapters on the language and presents only roughly enough of it to follow the rest of the book, pointing readers to other books for becoming an effective software engineer2. I agree, and I would go further: you can name the parts you need on one page.
Here is that page. The left column is what this chapter teaches. The right column is what you can skip for now, with the moment it becomes worth learning.
| Learn now | Why an analyst needs it | Skip for now | Learn it when |
|---|---|---|---|
| Values and types | Every column is one type, and type errors are the first errors you meet | Classes | You write a tool other people install |
| Lists, tuples, dicts, sets | Holding rows, keys, mappings and unique values | Decorators | You build a web app or a test suite |
| Slicing and comprehensions | Taking part of a sequence, building a new one | async and await | You call hundreds of web APIs at once |
| Functions with defaults | Turning a cleaning rule into something reusable | Generators in depth | Files no longer fit in memory |
| f strings | Labels and reports people can read | Type hints | Your code is shared and long lived |
| Loops, and when not to loop | Understanding why pandas is faster | Metaclasses, descriptors | Probably never |
| Errors and tracebacks | Fixing your own mistakes quickly | Writing your own exception classes | You maintain a library |
| Imports, pathlib, datetime | Finding files and handling dates correctly | Threads and processes | Speed matters and pandas is not enough |
If you set up Python in the first chapter, on why Python and how to set it up, you are ready. Everything below runs in a Jupyter Notebook or any Python 3.13 session. Python 3.13 is the current release in June 2025 (3.13.5 came out on 11 June)3, and Python 3.14 is scheduled for October 20254. Nothing in this chapter depends on the difference.
Example: Tariq's first fortnight
Tariq has two weeks before Grace wants a first answer about channel payback. He spends the first three days on the left column of the table, typing every example rather than reading it. He does not open the right column at all. On day four he writes the campaign cleaning function you will see at the end of this chapter. On day five he moves on to NumPy and pandas, which the next chapters cover. That order is deliberate: the language first, only as much as the data needs, then the tools that do the heavy lifting.
Five types of value you meet every day
A value is a single piece of data: a number, a piece of text, a yes or no. Every value in Python has a type, and the type decides what you can do with it. Five types cover almost everything in a business export.
| Type | What it holds | Where you meet it in a shop's data |
|---|---|---|
int | Whole numbers | Order IDs, quantities, money in pence |
float | Numbers with a decimal point | Conversion rates, averages, spend as the ad platform reports it |
str | Text (a "string" of characters) | Campaign names, product codes, email addresses |
bool | True or False | Is this a test order? Did the customer opt in? |
None | "No value here" | A missing discount code, a blank cell |
The trap is that an export file is text. A CSV file (Comma Separated Values, the plain text format most tools export) has no idea that 58 is a number. Until you convert it, Python treats it as two characters.
Example: one order row, five types
Here is one order from Fernhill Home's shop export, written as Python values. The function type() tells you the type of any value.
order_id = 100482 # int
order_value = 58.0 # float
channel = "paid_search" # str
is_test_order = False # bool
discount_code = None # no discount used
for value in [order_id, order_value, channel, is_test_order, discount_code]:
print(type(value).__name__, value)
# int 100482
# float 58.0
# str paid_search
# bool False
# NoneType None
Now the trap. A value read from a file arrives as text, and adding text joins it instead of adding it.
print("58" + "2") # 582, text is joined, not added
print(int("58") + 2) # 60, after converting to a number
print(float("58.00")) # 58.0
One more subtle trap with None. Python treats 0, an empty string and None all as "false" in an if statement. So if discount: cannot tell "the discount was zero" from "nobody recorded the discount". When the difference matters, and in money it usually does, test for None explicitly.
discount = 0
print(bool(discount)) # False, zero counts as false
print(discount is None) # False, but it is a known zero, not a missing value
Names point at values, they are not boxes
A variable is a name you give to a value so you can use it later. In spreadsheet terms it is a named cell. The rule for names is simple: lower case words joined by underscores, like order_value or spend_pence, which is the convention in Python's style guide, PEP 85. Choose names that say what the value is and in which unit. spend is ambiguous. spend_pence is not.
There is one behaviour that surprises almost everyone coming from spreadsheets. A name does not contain a value. It points at one. If two names point at the same list and you change the list through one name, the other name sees the change too.
Example: the backup list that was not a backup
Tariq keeps a list of the campaigns he has already checked. Before adding to it, he wants a backup.
campaigns = ["summer_sale", "brand_search"]
backup = campaigns # a second name for the SAME list
campaigns.append("candles_launch")
print(backup)
# ['summer_sale', 'brand_search', 'candles_launch'] the backup changed too
backup = campaigns did not copy anything. It gave the same list a second name. To get a real copy, ask for one.
campaigns = ["summer_sale", "brand_search"]
backup = campaigns.copy() # a new, separate list
campaigns.append("candles_launch")
print(backup)
# ['summer_sale', 'brand_search']
You will meet the same idea again in pandas, where it decides whether changing a filtered table also changes the original. Knowing it now saves an afternoon later.
Four containers, and the job each one does
Single values are rarely enough. Python has four built in containers, and each has a job in analysis. McKinney's third chapter covers them in more depth6. Here is what each one is for in a shop's data.
Lists: an ordered collection you can change
A list holds values in order, in square brackets. You can add, remove and change items. Use it for a sequence you are building up or walking through.
Example: a week of paid social spend
daily_spend = [312.40, 298.10, 305.75, 410.20, 388.00, 251.30, 240.90]
print(len(daily_spend)) # 7 days
print(sum(daily_spend)) # 2206.65
print(max(daily_spend)) # 410.2, the most expensive day
Tuples: a fixed group of values that belong together
A tuple looks like a list in round brackets, but it cannot be changed after you create it. That makes it the right shape for a record whose parts belong together, such as a date and a channel. Because it cannot change, a tuple can also serve as a key in a dictionary, which a list cannot.
Example: spend for one day and one channel
key = ("2025-05-12", "paid_social") # date and channel, fixed together
spend_by_day_channel = {key: 388.00}
print(spend_by_day_channel[("2025-05-12", "paid_social")]) # 388.0
Dictionaries: look things up by a name
A dictionary (a dict) maps keys to values, like a two column lookup table: campaign name to clean name, product code to category, country code to VAT rate. You look a value up by its key, and the lookup is fast no matter how large the dictionary grows. Since Python 3.7, a dictionary also keeps its items in the order you added them7, which makes printed results predictable.
The dictionary is the analyst's most underrated tool. Every "this means that" rule in a business belongs in one.
Example: the start of a campaign mapping
aliases = {
"fb_summer": "summer_sale", # Meta's old name for the summer sale
"brand": "brand_search",
}
print(aliases["fb_summer"]) # summer_sale
print(aliases.get("candles_launch", "candles_launch"))
# candles_launch .get() returns a default when the key is missing
The difference between aliases["x"] and aliases.get("x", default) matters. The square brackets fail loudly when the key is missing. .get() quietly returns the default. You want each one at a different moment, and the worked example uses both on purpose.
Sets: unique values, and comparing groups
A set holds unique values, with no order. Put a thousand rows of campaign names into a set and you get each name once. Sets also compare groups: which names are in this export but not in my list of known campaigns? That one question catches most tracking errors before they reach a report.
Example: finding names nobody has mapped yet
known = {"summer_sale", "candles_launch", "brand_search", "ceramics_retargeting"}
seen = {"summer_sale", "fb_summer", "brand", "candles_launch"}
print(sorted(seen - known)) # in the export, but not known
# ['brand', 'fb_summer']
Which container fits the job
Most questions about containers come down to three tests. This flow is the one I would pin above the desk.
The first question sends real tables to pandas straight away. Plain Python containers are for the small things around a table: the mapping, the list of files, the set of known names. That division of labour is the whole design of an analysis in Python.
Slicing: taking part of a list or a string
Slicing takes a piece of a sequence with square brackets and a colon. Two rules make it predictable. Counting starts at zero, so the first item is [0]. And a slice [start:stop] includes the start but stops just before the stop. Negative numbers count from the end, so [-1] is the last item and [-3:] the last three.
The rule "start included, stop excluded" sounds odd at first. It has one big advantage: [:3] and [3:] split a sequence into two parts with no overlap and nothing missing.
Example: the first and last days, and parts of a product code
daily_spend = [312.40, 298.10, 305.75, 410.20, 388.00, 251.30, 240.90]
print(daily_spend[0]) # 312.4, the first day
print(daily_spend[-1]) # 240.9, the last day
print(daily_spend[:3]) # [312.4, 298.1, 305.75], the first three days
print(daily_spend[-3:]) # [388.0, 251.3, 240.9], the last three days
Strings slice the same way. Fernhill Home's product codes have a fixed layout: category, number, colour.
sku = "CER-0142-BLU"
print(sku[:3]) # CER, the category (ceramics)
print(sku[4:8]) # 0142, the product number
print(sku[-3:]) # BLU, the colour
Fixed position slicing works only while every code has the same layout. The day a supplier sends a five letter category it breaks silently. For codes like these, sku.split("-") is safer, because it cuts at the separator wherever it sits.
Comprehensions: build a new list in one readable line
A comprehension builds a new list from an existing one in a single line: "give me this, for every item in that, where this condition holds". It replaces a three or four line loop and, once you can read it, says what it does more clearly.
The pattern is [expression for item in collection if condition]. The if part is optional. The same shape builds sets with curly brackets and dictionaries with key: value.
Example: pence to pounds, and only the expensive days
The shop's ad spend is stored in pence. Tariq wants pounds for a chart label, and a list of the days above £300.
spend_pence = [31240, 29810, 30575, 41020, 38800, 25130, 24090]
spend_pounds = [p / 100 for p in spend_pence]
print(spend_pounds)
# [312.4, 298.1, 305.75, 410.2, 388.0, 251.3, 240.9]
big_days = [p for p in spend_pence if p > 30000]
print(big_days)
# [31240, 30575, 41020, 38800]
Read the first comprehension aloud: "p divided by 100, for every p in spend pence". If a comprehension needs more than one condition or a nested loop to read like that, write the loop instead. Clear beats short.
Functions: write a rule once, call it everywhere
A function is a named, reusable piece of work. You give it inputs (arguments), it does something, and it hands back a result with return. For an analyst, a function is how a rule stops being something you do by hand and becomes something you can rerun, test and show to someone.
Three details matter in practice:
- Arguments with defaults.
def f(x, rate=0.2)lets the caller leaverateout. Defaults make the common case short and the unusual case possible. - A docstring. The text in triple quotes right under the
defline says what the function does. Notebooks and editors show it when you hover over the name. - Never a list or dict as a default. Python creates a default value once, when the function is defined, and reuses it on every call8. A default of
[]that the function appends to will keep growing across calls. UseNoneand create the list inside.
Example: the rule that cleans one campaign name
Fernhill Home's campaign names arrive in every spelling: capitals, spaces, hyphens, a year on the end. Tariq writes the rule once.
def clean_campaign(raw):
"""Turn a raw UTM campaign value into one consistent form."""
name = raw.strip().lower() # trim spaces, lower case
name = name.replace(" ", "_").replace("-", "_") # one separator only
parts = name.split("_")
if parts[-1].isdigit() and len(parts[-1]) == 4: # drop a trailing year
parts = parts[:-1]
return "_".join(parts)
print(clean_campaign(" SUMMER-Sale_2025 ")) # summer_sale
Each line does one thing, in the order a person would do it by hand. That is the point. Grace cannot read Python, but Tariq can read her this function line by line and she will follow it.
f strings: numbers people can read
An f string is text with values dropped into it. You put an f before the opening quote and the value in curly brackets: f"Spend: {spend}". After a colon inside the brackets you can say how to format the number, using what the documentation calls the format specification mini language9. Four codes cover most reporting:
:,.2ffor a thousands separator and two decimals:4,486.75:.1%for a share as a percentage with one decimal:49.7%:<22and:>12to pad text left or right, so columns line up!rto show a value with its quotes, so a trailing space becomes visible
Example: a label for the summer sale
total = 4486.75
share = 4486.75 / 9032.25
print(f"Summer sale: £{total:,.2f} ({share:.1%} of spend)")
# Summer sale: £4,486.75 (49.7% of spend)
print(f"{'summer_sale':<22}{total:>12,.2f}")
# summer_sale 4,486.75
A label like that goes straight into a chart title or an annotation. The chapter on words on charts, titles, annotations and captions explains why the title should carry the number and the point, and an f string is how you keep that title correct when the data changes.
Floating point, and why money needs care
Computers store decimal numbers in binary, and most decimal fractions, 0.1 among them, have no exact binary form. Python's float stores the nearest value it can, which is very slightly off. Usually the error is far too small to matter. In money, where totals have to reconcile to the penny, it matters. The Python tutorial gives this problem a whole chapter10.
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
Three practical consequences follow.
Never compare floats with ==. Use math.isclose(), which allows for the tiny error.
Rounding is not what you learned at school. Python's round() sends an exact half to the nearest even number, so round(0.5) is 0 and round(2.5) is 2. And because 2.675 is stored as slightly less than itself, round(2.675, 2) gives 2.67, an example the documentation itself uses11.
Adding many small floats drifts. A loop that adds 0.1 ten times ends at 0.9999999999999999. Since Python 3.12 the built in sum() uses a more careful algorithm and gets 1.012, but the loop you write yourself does not, and neither does a spreadsheet's running total.
import math
print(math.isclose(0.1 + 0.2, 0.3)) # True
total = 0.0
for _ in range(10):
total += 0.1
print(total) # 0.9999999999999999
print(round(2.675, 2), round(0.5), round(2.5)) # 2.67 0 2
There are two clean ways to handle money. Store it as whole pence in an int, which is exact, and divide by 100 only for display. Or use the decimal module, which does arithmetic in base ten exactly as accountants expect and lets you choose the rounding rule13. Always create a Decimal from text, Decimal("19.99"), never from a float, because Decimal(0.1) faithfully copies the float's error.
Example: three candles with 15% off
A customer buys three of Fernhill Home's soy candles at £19.99 each with a 15% newsletter discount. The line total is
where is the line total in pounds, the quantity, the unit price in pounds and the discount as a fraction. With , and , the exact result is , which rounds to £50.97. (If percentages as fractions feel rusty, see Foundations: percentages.)
print(3 * 19.99 * (1 - 0.15)) # 50.9745 here, but floats can land a hair off
from decimal import Decimal, ROUND_HALF_UP
line = Decimal("19.99") * 3 * (1 - Decimal("0.15"))
print(line) # 50.9745
print(line.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) # 50.97
print(Decimal(0.1)) # 0.1000000000000000055511151231257827021181583404541015625
# the same in whole pence: exact integers, with the rounding written out
gross_pence = 1999 * 3 # 5997
net_pence = (gross_pence * 85 + 50) // 100 # 5097, rounded half up
The float happened to give the right answer here. It will not always, and across 48,000 orders a year the small errors add up to a total that does not match the bank statement. My rule of thumb: money is stored in pence or as a Decimal, it is rounded once, at the end, with the rule written in the code, and floats are fine for everything that is a rate, a share or an average.
Loops, and why you will write fewer of them
A for loop repeats a step for every item in a collection. It is the most natural thing in the world: for every order, add the value to the total. You need loops, and this chapter uses them. But for arithmetic on large columns of numbers, a Python loop is slow, because Python checks the type of every value on every pass.
The alternative is vectorised work: one instruction applied to a whole array of numbers at once, carried out in fast compiled code. NumPy (version 2.3.0, released on 7 June 2025) and pandas (version 2.3.0, released on 5 June 2025) are built on this idea14. The next chapter explains NumPy and why it is fast. Here is the size of the difference.
Example: 48,000 orders, two ways to add them up
Fernhill Home takes about 48,000 orders a year at an average of £58. The code generates a year of order values with NumPy's random number generator (a fixed seed makes it repeatable) and adds them up twice.
import time
import numpy as np
rng = np.random.default_rng(seed=42)
order_values = rng.gamma(shape=4.0, scale=58 / 4, size=48_000)
print(round(order_values.mean(), 2)) # 57.98
start = time.perf_counter()
total_loop = 0.0
for value in order_values: # one order at a time
total_loop += value
loop_ms = (time.perf_counter() - start) * 1000
start = time.perf_counter()
total_vec = order_values.sum() # the whole array at once
vec_ms = (time.perf_counter() - start) * 1000
print(round(total_loop, 2), round(float(total_vec), 2)) # 2783063.37 2783063.37
print(f"loop {loop_ms:.1f} ms, vectorised {vec_ms:.2f} ms")
# loop 14.4 ms, vectorised 0.06 ms (your timings will differ)
Both give £2,783,063.37. When I ran it, the vectorised sum was about 250 times faster. On one year of orders, 14 milliseconds does not matter. On ten million GA4 events with five calculations each, it is the difference between a coffee and a lunch break.
So learn loops to understand what is happening, and use them for the things that genuinely go one at a time: a list of files, a handful of campaigns, a set of reports to write. For columns of numbers, let pandas and NumPy do the looping. You will find that most of the loops you would write in Python simply disappear.
Errors: how to read a traceback
When something goes wrong, Python stops and prints a traceback: the chain of calls that led to the error, and the error itself. Beginners read it from the top and panic. Read it from the bottom.
- The last line names the error type and gives a message:
KeyError: 'brand'. - The lines just above it show the line of your code where it happened, with markers under the exact part that failed.
- The lines further up show how the code got there, one function call per entry.
Python 3.13 highlights tracebacks in colour by default and keeps improving its messages, often adding a "Did you mean" suggestion for a misspelt name15. The errors you will meet most often in analysis are a handful: KeyError (a key is not in the dictionary), IndexError (a position past the end of a list), ValueError (the right type but an unusable value), TypeError (the wrong type, such as adding text to a number), NameError (a name you never defined, often a typo) and ModuleNotFoundError (a library that is not installed, or misspelt).
You can catch an error with try and except and handle it16. Do it sparingly. Catching an error to hide it is how wrong numbers reach a board meeting. Catch an error only when you know exactly what to do about it.
Example: the campaign nobody mapped
Tariq saved an early, strict version of his mapping as campaigns.py. It looks every name up with square brackets, and the dictionary has no entry for brand.
ALIASES = {"fb_summer": "summer_sale"}
def standard_campaign(raw):
name = raw.strip().lower()
return ALIASES[name]
print(standard_campaign("Brand"))
Traceback (most recent call last):
File "campaigns.py", line 7, in <module>
print(standard_campaign("Brand"))
~~~~~~~~~~~~~~~~~^^^^^^^^^
File "campaigns.py", line 5, in standard_campaign
return ALIASES[name]
~~~~~~~^^^^^^
KeyError: 'brand'
From the bottom: the key 'brand' is missing. One line up: it happened in return ALIASES[name] inside standard_campaign. One entry further up: that function was called from line 7. The fix is a business decision, not a coding one: what is brand? Tariq checks with Grace, who confirms it is the brand search campaign, and he adds it to the dictionary.
A second error you will meet in the first week, the moment a German supplier or a European tool sends a file:
float("58,00")
# ValueError: could not convert string to float: '58,00'
Python expects a full stop as the decimal mark. A decimal comma needs converting first, and the chapter on loading data shows how pandas does that for a whole file.
Imports: borrowing other people's work
Python itself is small. Most of its power comes from modules: files of code you load with import. Some ship with Python (the standard library: math, decimal, datetime, pathlib, csv). Others you install once, like NumPy and pandas. There are three forms you will use:
import mathloads the module, and you writemath.isclose(...).from decimal import Decimalloads one name, and you writeDecimal(...).import numpy as nploads a module under a short alias. The aliasesnpfor NumPy andpdfor pandas are so universal that you should use them too, or other people will struggle to read your code.
Put all imports at the top of the notebook or script. Anyone opening it sees at once what it depends on.
Example: the top of Tariq's notebook
import math
from datetime import datetime, timedelta, timezone
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path
from zoneinfo import ZoneInfo
import numpy as np
import pandas as pd
Standard library first, installed libraries second, each group in alphabetical order. If import pandas as pd fails with ModuleNotFoundError, pandas is not installed in the environment your notebook is using, which the setup chapter walks through.
Files and paths with pathlib
Analysis starts with files: this month's exports, last month's, the folder of Google Ads reports. A path is the address of a file. Windows writes it with backslashes, macOS and Linux with forward slashes, and code that glues paths together as text breaks when it moves between them.
The pathlib module solves this. A Path object knows how to join parts with /, find files by pattern, check whether a file exists, and read it17. McKinney's book opens files with the built in open() function, which still works. For new code, pathlib is clearer.
Example: finding every Google Ads export
Tariq keeps raw exports in data/raw, one file per month. This creates two empty example files so the code runs anywhere, then finds them.
from pathlib import Path
raw = Path("data") / "raw" # works on Windows and macOS alike
raw.mkdir(parents=True, exist_ok=True)
for month in ["2025-04", "2025-05"]:
(raw / f"google_ads_{month}.csv").write_text("Campaign,Cost\n", encoding="utf-8")
exports = sorted(raw.glob("google_ads_*.csv"))
for path in exports:
print(path.name, path.exists(), path.suffix)
# google_ads_2025-04.csv True .csv
# google_ads_2025-05.csv True .csv
Two habits worth forming now. Name files so they sort by date (year, then month), and keep raw exports untouched, writing anything cleaned into a separate folder. The final chapter of this series, on a reproducible workflow, builds on both.
Dates and times, and the midnight that moves
The datetime module gives you date, datetime and timedelta (a length of time)18. You parse text into a datetime with strptime, format it back with strftime, and subtract two datetimes to get the time between them.
The trap that costs real money is the time zone. Fernhill Home's shop exports order times in UTC (Coordinated Universal Time, the world's reference clock). Google Analytics 4 exports to BigQuery with two clocks at once: event_timestamp in UTC, and event_date in the property's own time zone19. UK time is UTC in winter and one hour ahead in summer. A datetime without a time zone attached (Python calls it "naive") cannot tell you which of those it means.
Attach the zone, then convert. The zoneinfo module knows every official time zone and its summer time rules. It uses the computer's own time zone data, and on Windows you may need to install the small tzdata package for it to work20.
Example: the order that changed month
A customer orders a set of linen napkins at 23:30 UTC on 30 June 2025. Which month does the sale belong to?
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
order_time_utc = datetime(2025, 6, 30, 23, 30, tzinfo=timezone.utc)
print(order_time_utc.astimezone(ZoneInfo("Europe/London")))
# 2025-07-01 00:30:00+01:00 July in York, June in UTC
parsed = datetime.strptime("30/06/2025 23:30", "%d/%m/%Y %H:%M")
print(parsed.tzinfo) # None: a naive datetime, zone unknown
print(parsed.strftime("%d %B %Y")) # 30 June 2025
print(datetime(2025, 6, 18) - timedelta(days=28)) # 2025-05-21 00:00:00
In York it was half past midnight on 1 July. Counted in UTC, the sale is June revenue. Counted in UK time, which is how Grace and the GA4 property count, it is July. Every order between 23:00 and midnight UTC on a summer month end moves month depending on which clock you use, and the shop export and GA4 will disagree until you pick one. Pick the business's local time, convert everything to it on the way in, and write that decision down.
Worked example: cleaning the campaign names
Now everything comes together. Tariq has May 2025's campaign spend from Google Ads and Meta, 14 rows, and he wants spend per campaign. The campaign names come from the UTM parameters (Urchin Tracking Module, the tags on every ad link) typed by three people over two years. If UTM tagging is new to you, the guide to clean campaign tracking with UTM parameters explains why they drift and how to stop it at the source. This section deals with the drift you already have.
The steps follow the flow below. The one step most tutorials leave out is the check before the totals.
Step 1: the raw rows
The data is built inline so you can run it. In real life it comes from two CSV exports, which the chapter on loading data covers. Spend is in pence, as integers, so every sum is exact.
# May 2025 spend by campaign, as the two ad platforms report it (spend in pence)
rows = [
{"source": "google", "campaign": "Summer_Sale", "spend_pence": 182000},
{"source": "google", "campaign": "summer sale", "spend_pence": 64550},
{"source": "google", "campaign": "summer-sale ", "spend_pence": 31275},
{"source": "meta", "campaign": "SUMMER_SALE_2025", "spend_pence": 148040},
{"source": "meta", "campaign": "fb_summer", "spend_pence": 22810},
{"source": "google", "campaign": "Brand", "spend_pence": 95630},
{"source": "google", "campaign": "brand_search", "spend_pence": 41200},
{"source": "google", "campaign": "BRAND ", "spend_pence": 12095},
{"source": "meta", "campaign": "Candles_Launch", "spend_pence": 118460},
{"source": "meta", "campaign": "candles launch", "spend_pence": 37725},
{"source": "google", "campaign": "candles-launch", "spend_pence": 54380},
{"source": "meta", "campaign": "ceramics_retargeting", "spend_pence": 66915},
{"source": "meta", "campaign": "Ceramics Retargeting", "spend_pence": 19340},
{"source": "meta", "campaign": "ceramics_rtg", "spend_pence": 8805},
]
This is a list of dictionaries: each row is a dictionary from column name to value, and the list holds the rows in order. It is the plain Python shape of a table, and exactly what pandas turns into a DataFrame in one line.
Step 2: look before you clean
Before writing a single rule, list the unique names. A set comprehension does it in one line, and !r (or repr()) shows the quotes, so trailing spaces become visible.
raw_names = {row["campaign"] for row in rows}
print(len(rows), len(raw_names)) # 14 14: every row has its own spelling
for name in sorted(raw_names):
print(repr(name))
# 'BRAND '
# 'Brand'
# 'Candles_Launch'
# 'Ceramics Retargeting'
# 'SUMMER_SALE_2025'
# 'Summer_Sale'
# 'brand_search'
# 'candles launch'
# 'candles-launch'
# 'ceramics_retargeting'
# 'ceramics_rtg'
# 'fb_summer'
# 'summer sale'
# 'summer-sale '
Fourteen rows, fourteen spellings. Look at the list and the patterns jump out: capitals, spaces where underscores should be, hyphens, trailing spaces, a year stuck on the end. Those are mechanical, so a function can fix them. Then there are three names that are different words for the same thing (fb_summer, brand, ceramics_rtg). No rule can guess those. They need a person's decision.
Step 3: the rules, as a function
This is the clean_campaign function from the section on functions, applied to every row. A set comprehension shows what is left.
after_rules = sorted({clean_campaign(row["campaign"]) for row in rows})
print(after_rules)
# ['brand', 'brand_search', 'candles_launch', 'ceramics_retargeting',
# 'ceramics_rtg', 'fb_summer', 'summer_sale']
Fourteen spellings became seven. The mechanical problems are gone. The three human ones remain, exactly as expected.
Step 4: the decisions, as a dictionary
The names no rule can fix go into a dictionary. This is the part Grace reads and signs off: three lines, one decision each. Next to it sits the list of campaigns that really exist, as a set.
ALIASES = {
"fb_summer": "summer_sale", # Meta's name for the summer sale in 2024
"brand": "brand_search", # the original brand search campaign
"ceramics_rtg": "ceramics_retargeting", # abbreviated by hand in Meta
}
KNOWN_CAMPAIGNS = {"summer_sale", "brand_search", "candles_launch", "ceramics_retargeting"}
def standard_campaign(raw, aliases=ALIASES):
"""Clean a raw campaign name, then apply the agreed aliases."""
name = clean_campaign(raw)
return aliases.get(name, name) # unchanged if there is no alias
for row in rows:
row["campaign_clean"] = standard_campaign(row["campaign"])
Notice the uppercase names. Python has no true constants, but ALIASES in capitals tells every reader "this is a fixed setting, not a working variable". Notice too that aliases.get(name, name) returns the name itself when there is no alias. That is right here, because most names need no alias. It is also the reason for the next step.
Step 5: fail loudly on anything new
.get() lets an unknown name through untouched. Next month, someone will launch a campaign called xmas_gifts or type sumer_sale, and it will pass through silently as its own campaign. So Tariq compares the clean names against the known list with a set difference, and stops if anything is left over.
unmapped = {row["campaign_clean"] for row in rows} - KNOWN_CAMPAIGNS
if unmapped:
raise ValueError(f"Unknown campaigns, add them to ALIASES: {sorted(unmapped)}")
print(unmapped) # set(): nothing unknown this month
This is the step that turns a script into a control. When a new name appears, the run stops with a message that says exactly what to do. Someone asks the question, the answer goes into the dictionary, and the decision is on record for good. A spreadsheet filter would have quietly shown one more row.
Step 6: total spend per campaign
A small function totals spend by any column. It uses a dictionary as a running tally, with .get(key, 0) to start each new campaign at zero.
def spend_by(rows, key):
"""Total spend in pence for each value of the given column."""
totals = {}
for row in rows:
totals[row[key]] = totals.get(row[key], 0) + row["spend_pence"]
return totals
before = spend_by(rows, "campaign")
after = spend_by(rows, "campaign_clean")
total = sum(after.values())
for name, pence in sorted(after.items(), key=lambda item: item[1], reverse=True):
print(f"{name:<22}£{pence / 100:>9,.2f} {pence / total:>6.1%}")
print(f"{'total':<22}£{total / 100:>9,.2f}")
# summer_sale £ 4,486.75 49.7%
# candles_launch £ 2,105.65 23.3%
# brand_search £ 1,489.25 16.5%
# ceramics_retargeting £ 950.60 10.5%
# total £ 9,032.25
The lambda item: item[1] is a tiny unnamed function that tells sorted() to sort by the second part of each pair, the spend. You will see lambda occasionally. You rarely need to write one yourself.
Step 7: check the total, then look at the difference
Cleaning must never create or lose money. One line proves it did not.
assert total == sum(before.values()) # 903225 pence either way
assert stops the run if the condition is false. Because spend is in whole pence, the comparison is exact. With floats, this check would need math.isclose(), and a real mismatch could hide inside the tolerance.
Here is what the raw names would have told Grace.
And here is the truth.
The largest raw name showed £1,820. The real summer sale spent £4,486.75, two and a half times as much and very nearly half the month's paid media. Any return on ad spend calculated per raw name would have been wrong in every row, because the revenue in GA4 carries the same messy names and would have been split up in the same arbitrary way. For the choice of chart itself, horizontal bars sorted by size are the right form for comparing amounts across named categories, as the chapter on showing amounts and proportions explains.
The same in pandas, as a preview
In the coming chapters this becomes shorter. pandas applies string methods to a whole column at once, and .replace() takes the same ALIASES dictionary. Do not worry about the details yet: the chapters on pandas, on cleaning and on group by explain every line. The point is that the dictionary, the decision Grace signed off, carries over unchanged.
import pandas as pd
df = pd.DataFrame(rows)
df["campaign_clean"] = (
df["campaign"].str.strip().str.lower()
.str.replace(r"[ \-]", "_", regex=True) # one separator
.str.replace(r"_\d{4}$", "", regex=True) # drop a trailing year
.replace(ALIASES) # the agreed decisions
)
print(df.groupby("campaign_clean")["spend_pence"].sum().sort_values(ascending=False) / 100)
# summer_sale 4486.75
# candles_launch 2105.65
# brand_search 1489.25
# ceramics_retargeting 950.60
What to skip for now, and why that is fine
Every Python course reaches classes and object oriented programming early, because that is how software is built. Analysis is built differently: data in, a sequence of transformations, a result out. McKinney leaves classes out of his language chapters for the same reason2. Here is what you can leave for later, and the sign that later has arrived.
- Classes. You will use objects all the time (a DataFrame is one), but you rarely need to define your own. Learn them when you write a tool other people install and call.
- Decorators. The
@somethinglines above a function. You will see them in testing tools and web frameworks. Learn them when you write tests that need them, in the chapter on a reproducible workflow. - async and await. For programs that wait on many network requests at once. Analysis almost never does.
- Generators in depth. Useful when a file is too large for memory. pandas can read large files in chunks, which covers most cases.
- Type hints. The
name: strnotes in function definitions. Helpful in shared, long lived code, optional in a notebook. - Regular expressions beyond the basics. The pandas preview above uses two short ones. The chapter on cleaning data covers the handful of patterns analysts really use.
None of this is beneath you. It is simply not on the path between an export and an answer. You can always come back.
My view
The best analysts I know of do not write the most impressive Python. They write the most boring Python: short functions with clear names, one dictionary per business rule, a check that stops the run when the data surprises them, money in pence and every time with its zone. That style is not a beginner's compromise. It is what makes an analysis something a business can trust and rerun.
So learn the slice in this chapter until it feels ordinary, then stop learning the language and start learning the tools. The jump from Python to pandas is where the real productivity is, and the next chapters make it. Data science and analytics dashboards are a core part of my data science work for clients, and the habits in this chapter are the ones I insist on there too.
Conclusion
An analyst needs a small part of Python, and needs it well: the five types of value, names that point rather than contain, four containers with distinct jobs, slicing, comprehensions, functions with sensible defaults, f strings, a healthy suspicion of floats around money, enough loops to know when not to write them, tracebacks read from the bottom, imports, pathlib for files and datetime with real time zones. Classes, decorators and async can wait.
The worked example is the shape of most real cleaning: look at the unique values, fix what rules can fix in a function, put human decisions in a dictionary someone can sign off, stop on anything unknown, and prove the total did not move. For Fernhill Home it turned 14 confusing names into four campaigns and showed that the summer sale took half of May's paid media.
The next chapter, on NumPy, explains why the vectorised sum was 250 times faster and how to think in whole arrays instead of single values. If you would like help bringing your own exports into this kind of shape, the free workshop is the place to start.
