Loading business data into pandas: CSV, Excel, GA4, ad platforms and SQL, read correctly
TL;DR
Difficulty: Intermediate
Most wrong numbers start at loading, and pandas never warns you.
- A CSV holds characters, not types: spell out separator, number format, encoding, ID types and the date format.
- Prove every load with the handshake: rows, one money total and the date range against the source.
- Know each source's trap: test, staff and refund rows and UTC times in the shop export, totals rows in Google Ads, text numbers and nested lists from Meta, machine opens in the newsletter, nested parameters and duplicates in GA4.
- Never add platform conversions together, and keep personal data out of the analysis table.
Every analysis starts with a file somebody else made, and each one has a quirk that quietly changes the numbers. Here is how to load the example shop's five exports, a database and a shared sheet into pandas, with every decision written down and a three number check that proves the load is right.
Loading is where the analysis is won or lost
Every analysis starts with a file somebody else made. The shop exports orders, Google Analytics sends events to BigQuery, Google Ads and Meta hand over reports, the newsletter tool produces a spreadsheet. None of them was built for you. Each one carries a small quirk that, if you miss it, quietly changes every number that follows.
The previous chapter on Series and DataFrames built tables by hand. This chapter fills them with the real thing. By the end you will have loaded the example shop's five exports, plus a database and a shared sheet, into tidy DataFrames, and you will know how to prove that each load is right.
Wes McKinney's book makes a point in its chapter on data loading that is worth putting at the front: in a text file like a CSV, "column data types are not part of the data format"1. A CSV is only characters. Whether "0042117" is a number or a customer ID, whether "03/06/2025" is the third of June or the sixth of March, whether "1,234" is one thousand or one point two, is a guess, and pandas guesses for you unless you tell it. This chapter is about telling it.
I ran every block below with Python 3.13, pandas 2.3.1, NumPy 2.3, pyarrow 21, openpyxl 3.1.5 and SQLAlchemy 2.0, the versions current at the end of July 20252. If you have not set up Python yet, the setup chapter covers it, and pip installs the extras with pip install pandas pyarrow openpyxl sqlalchemy.
If you only read one section
For the person who commissions an analysis and will not read the code, here is the whole point.
- Most wrong numbers are born at loading, not in the model. A totals row summed with the campaigns triples ad spend. A refund row counted as an order inflates sales. A UTC timestamp moves orders into the wrong month. None of these raise an error.
- A load is only correct when it matches the source. Ask your analyst for three numbers per export: rows, one money total and the date range, each compared with what the source system shows on screen. I call it the handshake. If they cannot show it, the report is not finished.
- Every source counts differently, on purpose. In this chapter's example the shop has 3,960 real orders in June, GA4 sees 3,050 of them, Google Ads claims 1,162 conversions and Meta claims 702 purchases. All four are "right" by their own rules. Adding them together is wrong.
- Personal data comes in with the export. Load only the columns you need and replace customer identifiers with pseudonyms before anyone starts exploring.
If you want help building this kind of loading layer for your own business, it is part of my Data Science work.
The handshake: three numbers every load must match
Here is the rule of thumb I would put above everything else in this chapter. After reading any export, before you look at a single chart, compare three numbers with the system it came from:
- Rows. How many lines did the source export, and how many rows does your DataFrame have?
- One money total. Sales, spend or revenue, summed in pandas, against the same figure on the source's own screen or totals row.
- The date range. The first and last timestamp in your data, against the period you asked for.
If all three match, the file arrived whole and pandas read it the way the source meant it. If one is off, you have found a loading problem while it is still quick to fix, rather than a "strange result" two weeks later. The handshake does not prove the data is clean (that is the job of the next chapter, on cleaning data), it proves you read it faithfully.
Example: the handshake on the shop's June export
Ardmore Home is the example shop of this series: an online homeware shop in Sligo (candles, ceramics, textiles, ardmorehome.example), founded by Áine. Darragh, the analyst, has the standing question: "Which channel really pays back, and where should next month's budget go?"
Darragh opens the shop's admin and writes down three numbers for June 2025: the export has 4,090 lines below the header, the totals line says €257,190.57, and the period is 1 to 30 June. Later in this chapter his DataFrame shows 4,090 rows, a sum of €257,190.57 and timestamps from 1 June 00:13 to 30 June 23:06. The handshake holds. Only then does he start asking what those rows mean.
The loading checklist
The handshake sits in the middle of a short routine. Each step exists because a real export breaks without it.
The first step matters more than it looks. Never "fix" an export by opening it in Excel and saving it again. Excel will happily turn customer IDs into numbers, dates into its own format and the file's encoding into something else. Keep the original, read it with code, and every change you make is written down in that code.
Example: what Darragh looks at before reading
Before any pandas, Darragh looks at the first two lines of each file as plain text, in a terminal or a text editor:
head -n 2 exports/orders_2025_06.csv
He is looking for four things: which character separates columns (comma or semicolon), how numbers are written ("1,234.50" or "1.234,50"), whether there are title lines above the header, and any odd characters that hint at an encoding problem. Thirty seconds, and he knows which parameters the reader will need.
Formats and the pandas readers that open them
pandas has a reader for every common format, all named read_ something, and they share most of their parameters2. Here is the map for the sources a business actually has.
| Source | Typical format | pandas reader | Extra package | Typical trap |
|---|---|---|---|---|
| Shop order export | CSV | read_csv | none | encoding, thousands separator, UTC times, test and refund rows |
| Google Ads report | CSV | read_csv | none | title lines above the header, totals rows at the bottom |
| Meta Ads via the API | JSON | json.load and json_normalize | none | numbers sent as text, nested action lists |
| Newsletter tool | Excel | read_excel | openpyxl | title block above the table, inflated opens |
| GA4 in BigQuery | SQL query | BigQuery client to_dataframe or pandas_gbq.read_gbq | google cloud bigquery or pandas gbq | nested event parameters, UTC versus property time zone |
| Shop database | SQL query | read_sql | SQLAlchemy and a driver | types the database stores differently |
| Shared planning sheet | Google Sheets | gspread, then DataFrame | gspread | numbers typed as text |
| Your own clean copies | Parquet | read_parquet | pyarrow | none, which is the point |
Make the five exports
Real exports cannot be shared, so the code in this section generates the example shop's files for June 2025 with a fixed random seed. If you have your own exports, skip to the next section and point the readers at your files. If you want to follow along, copy these blocks into a notebook in order. They create a folder exports with every file this chapter reads.
Example: the setup and the shop's order export
import json
import os
from pathlib import Path
import numpy as np
import pandas as pd
CUR = "EUR" # the shop's currency
TZ = "Europe/Dublin" # the shop's local time zone
SHOP = "ardmorehome.example"
AOV = 66 # average order value in euro
k = AOV / 58 # scales every money amount
rng = np.random.default_rng(2025) # fixed seed: the same data on every run
EXPORTS = Path("exports")
EXPORTS.mkdir(exist_ok=True)
The shop stores order times in UTC, like most shop systems. The order values are skewed, as real baskets are, with six large trade orders on top.
# 3,960 real orders in June 2025, stored in UTC
n_real = 3960
secs = np.sort(rng.uniform(0, 30 * 24 * 3600, n_real))
created = (pd.Timestamp("2025-06-01") + pd.to_timedelta(secs, unit="s")).floor("s")
values = rng.lognormal(mean=np.log(AOV * 0.935) - 0.18, sigma=0.6, size=n_real)
values[rng.choice(n_real, 6, replace=False)] = rng.uniform(1100, 2400, 6) * k # trade orders
values = values.round(2)
customers = rng.integers(1, 21000, n_real)
real = pd.DataFrame({
"Order ID": [f"AH{100001 + i}" for i in range(n_real)],
"Created at (UTC)": created,
"Customer ID": [f"{c:07d}" for c in customers], # seven digits, leading zeros
"Email": [f"customer{c}@mail.example" for c in customers],
"Type": "order",
"Tags": "",
"Discount code": rng.choice(["", "n/a", "SUMMER10", "WELCOME"], n_real,
p=[0.55, 0.25, 0.12, 0.08]),
"First item": rng.choice(["Fig candle", "Stoneware mug", "Linen throw",
"Café au lait bowl", "Wool cushion", "Crème candle"], n_real),
"Total": values,
})
Now the things every real shop export contains and no tutorial does: test orders, staff orders and refunds written as separate rows.
# test orders and staff orders, mixed into the same file
test = real.sample(14, random_state=1).assign(
Email=f"test@{SHOP}", Tags="test", Total=1.00, **{"Customer ID": "0000001"})
staff = real.sample(22, random_state=2).assign(Tags="staff")
staff["Total"] = (staff["Total"] * 0.7).round(2)
extra = pd.concat([test, staff])
extra["Order ID"] = [f"AH{200001 + i}" for i in range(len(extra))]
# refunds arrive as their own rows with a negative total
ref = real.sample(118, random_state=3).copy()
ref["Type"] = "refund"
ref["Created at (UTC)"] += pd.to_timedelta(rng.uniform(1, 9, 118), unit="D")
ref = ref[ref["Created at (UTC)"] < "2025-07-01"] # July refunds go in July's file
half = rng.random(len(ref)) < 0.4
ref["Total"] = np.where(half, -(ref["Total"] * 0.5).round(2), -ref["Total"])
shop = (pd.concat([real, extra, ref])
.sort_values("Created at (UTC)").reset_index(drop=True))
shop["Created at (UTC)"] = shop["Created at (UTC)"].dt.strftime("%d/%m/%Y %H:%M:%S")
shop["Total"] = shop["Total"].map(lambda v: f"{v:,.2f}") # "1,234.50"
shop["Currency"] = CUR
shop.to_csv(EXPORTS / "orders_2025_06.csv", index=False, encoding="utf-8-sig")
# the same file after a colleague opened it in Excel and saved it as plain CSV
shop.to_csv(EXPORTS / "orders_2025_06_resaved.csv", index=False, encoding="cp1252")
print(len(shop))
# 4090
Example: the ad platforms, the newsletter, GA4 and the database
The Google Ads report gets two title lines on top and four totals rows at the bottom, as a downloaded campaign report often has.
names = ["Search | Brand", "Search | Candles", "Search | Ceramics", "Search | Textiles",
"Shopping | All products", "Shopping | Best sellers", "PMax | Homeware"]
types = ["Search"] * 4 + ["Shopping"] * 2 + ["Performance Max"]
clicks = np.array([2210, 5120, 3980, 3310, 7720, 3650, 2380])
gads_src = pd.DataFrame({
"Campaign": names, "Campaign type": types, "Currency code": CUR,
"Cost": (np.array([640, 1890, 1420, 1210, 2350, 1180, 710]) * k).round(2),
"Impr.": clicks * rng.integers(14, 30, 7), "Clicks": clicks,
"Conversions": [182.0, 214.5, 151.0, 133.0, 258.5, 162.0, 61.0],
})
totals = [gads_src[gads_src["Campaign type"] == t].sum(numeric_only=True)
.rename(f"Total: {t}") for t in ["Search", "Shopping", "Performance Max"]]
totals.append(gads_src.sum(numeric_only=True).rename("Total: Account"))
tot = pd.DataFrame(totals).rename_axis("Campaign").reset_index().assign(**{"Currency code": CUR})
report = pd.concat([gads_src, tot])
report["Cost"] = report["Cost"].map(lambda v: f"{v:,.2f}")
report["Impr."] = report["Impr."].map(lambda v: f"{int(v):,}")
report["Clicks"] = report["Clicks"].map(lambda v: f"{int(v):,}")
with open(EXPORTS / "google_ads_2025_06.csv", "w", encoding="utf-8") as f:
f.write("Campaign report\n1 June 2025 - 30 June 2025\n")
report.to_csv(f, index=False)
Meta's numbers come from its Marketing API, which answers in JSON and sends numbers such as spend as text3. The generated file copies that shape.
meta_names = ["Prospecting | Candles", "Prospecting | Ceramics", "Retargeting | Viewed product",
"Retargeting | Basket", "Advantage+ | Homeware"]
spend = (np.array([1680.40, 1325.10, 940.75, 610.30, 1643.45]) * k).round(2)
purchases = [168, 121, 157, 129, 127]
payload = {"data": [
{"campaign_name": c, "date_start": "2025-06-01", "date_stop": "2025-06-30",
"spend": f"{s:.2f}", "account_currency": CUR,
"actions": [{"action_type": "link_click", "value": str(int(s * 3.1 / k))},
{"action_type": "purchase", "value": str(p)}]}
for c, s, p in zip(meta_names, spend, purchases)]}
(EXPORTS / "meta_insights_2025_06.json").write_text(json.dumps(payload, indent=2))
The newsletter tool exports an Excel file with a title block above the table.
nl = pd.DataFrame({
"Campaign": ["June edit", "New candles", "Ceramics restock", "Summer sale 1",
"Summer sale 2", "Textiles", "Last call", "Midsummer"],
"Sent": pd.to_datetime([f"2025-06-{d:02d} 08:00" for d in (3, 6, 10, 13, 17, 20, 24, 27)]),
"Recipients": [18240, 18310, 18355, 18420, 18460, 18530, 18580, 18610],
})
nl["Delivered"] = (nl["Recipients"] * rng.uniform(0.985, 0.992, 8)).astype(int)
nl["Unique opens"] = (nl["Delivered"] * rng.uniform(0.55, 0.62, 8)).astype(int)
nl["Unique clicks"] = (nl["Delivered"] * rng.uniform(0.018, 0.031, 8)).astype(int)
nl["Unsubscribes"] = rng.integers(9, 30, 8)
with pd.ExcelWriter(EXPORTS / "newsletter_2025_06.xlsx", engine="openpyxl") as xw:
title = pd.DataFrame([["Campaign performance"], ["1 to 30 June 2025"], [""]])
title.to_excel(xw, sheet_name="Campaigns", index=False, header=False)
nl.to_excel(xw, sheet_name="Campaigns", index=False, startrow=3)
GA4's BigQuery export cannot be generated locally, so the next block writes purchase events in the same nested shape the export uses (event parameters as a list of key and value records, ecommerce and traffic source as nested records)4, one JSON object per line. GA4 sees only part of the orders, because some visitors decline consent or block the tag, and 41 purchases are recorded twice because the thank you page was reloaded.
media = {"organic": ("google", "organic"), "cpc": ("google", "cpc"),
"paid_social": ("facebook", "paid_social"), "email": ("newsletter", "email"),
"direct": ("(direct)", "(none)"), "referral": ("homesmagazine.example", "referral")}
seen = real.sample(3050, random_state=4).sort_values("Created at (UTC)") # consent, blockers
seen["ch"] = rng.choice(list(media), len(seen), p=[0.31, 0.24, 0.16, 0.12, 0.12, 0.05])
events = pd.concat([seen, seen.sample(41, random_state=5)]) # page reloads
stamp = events["Created at (UTC)"].astype("int64") // 1000 + rng.integers(0, 4_000_000, len(events))
with open(EXPORTS / "ga4_purchases_2025_06.jsonl", "w", encoding="utf-8") as f:
for (_, r), t in zip(events.iterrows(), stamp):
source, medium = media[r["ch"]]
f.write(json.dumps({
"event_date": pd.Timestamp(int(t), unit="us", tz="UTC").tz_convert(TZ).strftime("%Y%m%d"),
"event_timestamp": int(t), "event_name": "purchase",
"event_params": [
{"key": "ga_session_id", "value": {"string_value": None, "int_value": int(t // 10**6)}},
{"key": "page_location", "value": {"string_value": f"https://{SHOP}/checkout/thanks",
"int_value": None}}],
"session_traffic_source_last_click": {"manual_campaign": {"source": source, "medium": medium}},
"ecommerce": {"transaction_id": r["Order ID"], "purchase_revenue": float(r["Total"])},
}) + "\n")
Last, a stand in for the shop's own database: an in memory SQLite database with the customer table.
from sqlalchemy import create_engine, text
engine = create_engine("sqlite://")
pd.DataFrame({
"customer_id": [f"{c:07d}" for c in range(1, 21001)],
"first_order": pd.Timestamp("2021-03-01") + pd.to_timedelta(rng.integers(0, 1580, 21000), unit="D"),
"marketing_opt_in": rng.random(21000) < 0.62,
}).to_sql("customers", engine, index=False)
Reading a CSV is a set of decisions, not one line
pd.read_csv("file.csv") works on the first try often enough that people trust it. It always returns a table. Whether that table means what the file meant is another matter, because every guess pandas makes is silent.
Example: the naive read of the shop export
naive = pd.read_csv(EXPORTS / "orders_2025_06.csv")
print(naive.dtypes[["Customer ID", "Total"]])
# Customer ID int64
# Total object
print(naive["Customer ID"].head(3).tolist())
# [11926, 4212, 10684]
Two silent errors in two lines. The customer IDs became integers, so "0011926" lost its leading zeros and will never match the customer table, which stores seven characters. And the order totals came back as object, pandas' word for text, because "1,234.50" is not a number until you tell pandas that the comma separates thousands. Sum that column and you get an error at best, a concatenated string at worst.
Encoding: why the same file reads on one machine and fails on another
A file is bytes. The encoding is the agreement about which bytes mean which letters. Shop systems and most tools write UTF 8, the encoding that covers every alphabet. Excel likes to add a byte order mark (BOM), three invisible bytes at the start that announce "this is UTF 8". Python calls that variant utf-8-sig5. pandas strips the mark on its own when it reads UTF 8, so this file reads fine either way, but writing encoding="utf-8-sig" states what you expect and documents it.
The trouble starts when someone opens the export in Excel on Windows and saves it as plain "CSV". Excel then writes Windows 1252 (Python's name is cp1252), an older encoding in which "é" and "è" are single bytes that are not valid UTF 85.
Example: the file a colleague saved again
try:
pd.read_csv(EXPORTS / "orders_2025_06_resaved.csv")
except UnicodeDecodeError as err:
print(err)
# 'utf-8' codec can't decode byte 0xe8 in position 168: invalid continuation byte
resaved = pd.read_csv(EXPORTS / "orders_2025_06_resaved.csv", encoding="cp1252")
print(resaved["First item"].unique()[:3])
# ['Crème candle' 'Fig candle' 'Wool cushion']
Byte 0xe8 is "è" in Windows 1252. The error tells you exactly where to look: position 168 is in the first data line, in "Crème candle". The fix is one parameter. The lesson is bigger: an error is the good outcome. The bad outcome is reading the file as Latin 1 by habit, which never fails, and finding "Crème" written as "Crème" in a report three weeks later.
The shop export, read properly
Now the full read, with every decision written down. dtype fixes the types of the identifier columns, thousands explains the number format, na_values adds the shop's own word for "nothing" to the usual empty cells, and date_format tells pandas the dates are day first, so it never has to guess between the third of June and the sixth of March. I use the "string" type for identifiers: the pandas 2.2 release notes announced that pandas 3.0 will give text its own string type by default6, and an ID column should be text in any case.
Example: Darragh's read of the June orders
orders = pd.read_csv(
EXPORTS / "orders_2025_06.csv",
encoding="utf-8-sig", # says out loud: UTF 8, with a BOM
thousands=",", # "1,234.50" becomes 1234.5
dtype={"Order ID": "string", "Customer ID": "string", "Email": "string"},
na_values=["n/a"], # the shop's word for nothing
parse_dates=["Created at (UTC)"],
date_format="%d/%m/%Y %H:%M:%S", # day first, no guessing
)
orders.columns = (orders.columns.str.lower()
.str.replace(r"\W+", "_", regex=True).str.strip("_"))
print(orders.dtypes)
# order_id string[python]
# created_at_utc datetime64[ns]
# customer_id string[python]
# email string[python]
# type object
# tags object
# discount_code object
# first_item object
# total float64
# currency object
The last two lines turn column names like "Created at (UTC)" into created_at_utc: lower case, underscores, no spaces or brackets (\W matches anything that is not a letter, digit or underscore). That makes them easy to type and keeps the original meaning, including the "UTC" that will matter in a moment.
Example: the handshake in code
print("rows:", len(orders))
# rows: 4090
print("total:", round(orders["total"].sum(), 2))
# total: 257190.57
print("first:", orders["created_at_utc"].min(), " last:", orders["created_at_utc"].max())
# first: 2025-06-01 00:13:30 last: 2025-06-30 23:06:45
assert orders["customer_id"].str.len().eq(7).all()
assert not orders.duplicated(["order_id", "type"]).any() # a refund reuses its order number
Rows, total and range match what Darragh wrote down from the admin. The two assert lines turn expectations into checks that stop the notebook if they ever fail: every customer ID keeps its seven characters, and no order number appears twice with the same type. The second one is written that way for a reason. Order numbers are not unique in this export, because a refund row carries the number of the order it refunds. Had Darragh asserted plain uniqueness, the check would have failed, and that failure would have taught him something true about the file.
Time zones: the order placed at five past midnight
The shop stores times in UTC. Áine thinks in Sligo time. In June, Ireland is on summer time (Irish Standard Time), one hour ahead of UTC, so an order at 23:06 UTC on 30 June was placed at 00:06 on 1 July in Sligo. pandas handles this in two steps: tz_localize("UTC") says what the naive timestamps are, and tz_convert translates them2.
Example: which June orders belong to July
orders["created_at"] = (orders["created_at_utc"]
.dt.tz_localize("UTC")
.dt.tz_convert(TZ))
next_month = orders["created_at"].dt.month == 7
print(next_month.sum())
# 2
print(orders.loc[next_month, ["created_at_utc", "created_at"]])
# created_at_utc created_at
# 4088 2025-06-30 23:06:41 2025-07-01 00:06:41+01:00
# 4089 2025-06-30 23:06:45 2025-07-01 00:06:45+01:00
Two orders on their own would be grand. The point is the direction of the error: the same hour at the start of the month is missing from this file entirely, because orders placed between midnight and 1am Irish time on 1 June sit in the May export. Monthly figures built from UTC exports are shifted by an hour at both ends, by two hours in summer for a shop in Germany or Austria, and the shift grows if you compare days of the week or hours of the day. Decide once which clock the business reports in, convert everything to it at loading, and keep the UTC column for joins. Time zones get their own treatment in the chapter on time series later in this series.
Test orders, staff orders and refunds are rows, not sales
A shop export is a log of events, not a list of sales. In this one, three kinds of rows are not what a sales report means by "orders": test orders the developers placed, staff orders at a discount, and refunds, written as separate rows with negative totals.
Example: from 4,090 rows to 3,960 orders
orders["tags"] = orders["tags"].fillna("")
is_test = orders["tags"].str.contains("test")
is_staff = orders["tags"].str.contains("staff")
print(is_test.sum(), is_staff.sum(), orders["type"].eq("refund").sum())
# 14 22 94
sales = orders[~is_test & ~is_staff]
real_orders = sales[sales["type"].eq("order")]
print("orders:", len(real_orders))
# orders: 3960
print("gross:", round(real_orders["total"].sum(), 2))
# gross: 261239.75
print("refunds:", round(sales.loc[sales["type"].eq("refund"), "total"].sum(), 2))
# refunds: -5041.68
print("net:", round(sales["total"].sum(), 2))
# net: 256198.07
print("average order value:", round(real_orders["total"].mean(), 2))
# average order value: 65.97
The result: 3,960 real orders, €261,239.75 gross, €5,041.68 refunded, €256,198.07 net, and an average order value of €65.97. Had Darragh counted rows as orders, he would have reported 4,090 orders and an average of €62.88 (the file total divided by all rows), with refunds pulling it down and test orders at €1 diluting it. That is an error of almost 5% on the shop's most watched number, from a file that loaded without a single warning.
Notice that the refunds stay in sales, labelled, rather than disappearing. Net revenue needs them. Whether a refund dated in June for a May order belongs to May or June is a business decision, not a pandas one: write the rule down once and apply it in code.
Report files: title lines above, totals rows below
Ad platform reports are built to be read by people, so they carry a title, a date range and totals. In a DataFrame those lines are poison. A title line becomes the header. A totals row becomes a campaign, and every sum counts the spend twice or more.
Example: the Google Ads report and the spend that tripled
gads_raw = pd.read_csv(EXPORTS / "google_ads_2025_06.csv", skiprows=2, thousands=",")
print(gads_raw[["Campaign", "Cost"]].tail(4))
# Campaign Cost
# 7 Total: Search 5871.73
# 8 Total: Shopping 4016.90
# 9 Total: Performance Max 807.93
# 10 Total: Account 10696.56
print("naive sum:", round(gads_raw["Cost"].sum(), 2))
# naive sum: 32089.68
skiprows=2 jumps over the title and the date range so the third line becomes the header. The totals stay in. Summed naively, Google Ads spend for June is €32,089.68, three times the real €10,696.56, because each euro is counted once in its campaign, once in its campaign type total and once in the account total.
You could cut the bottom lines with skipfooter, but that counts lines and breaks the day the report has one campaign more. The sturdier way is to filter on what the totals rows say, and then use the account total for the handshake instead of throwing it away.
is_total = gads_raw["Campaign"].str.startswith("Total:")
gads = gads_raw[~is_total].copy()
account_total = gads_raw.loc[gads_raw["Campaign"].eq("Total: Account"), "Cost"].item()
assert abs(gads["Cost"].sum() - account_total) < 0.01 # the report checks itself
print(len(gads), round(gads["Cost"].sum(), 2), gads["Conversions"].sum())
# 7 10696.56 1162.0
Seven campaigns, €10,696.56 of spend, and 1,162 conversions by Google Ads' own count. The fractional conversions in the data (214.5, 258.5) are a reminder that the platform can split one sale between several clicks. Those 1,162 are Google's answer under Google's rules. Keep them as their own column, never add them to anyone else's count.
Meta and other APIs: nested JSON into a flat table
APIs answer in JSON: objects inside lists inside objects. pandas cannot put a list into a cell and still sum it, so the job is to flatten. pd.json_normalize does that: it turns nested keys into columns joined with dots, and with record_path it unrolls a list into rows while carrying fields from the parent along with meta7.
Example: Meta purchases per campaign
with open(EXPORTS / "meta_insights_2025_06.json", encoding="utf-8") as f:
payload = json.load(f)
actions = pd.json_normalize(payload["data"], record_path="actions",
meta=["campaign_name", "spend", "account_currency"])
print(actions.head(3))
# action_type value campaign_name spend account_currency
# 0 link_click 5209 Prospecting | Candles 1912.18 EUR
# 1 purchase 168 Prospecting | Candles 1912.18 EUR
# 2 link_click 4107 Prospecting | Ceramics 1507.87 EUR
One row per campaign and action type. A pivot turns the action types into columns, pd.to_numeric turns the text into numbers, and an assert checks the currency.
meta = (actions.pivot(index=["campaign_name", "spend", "account_currency"],
columns="action_type", values="value")
.reset_index().rename_axis(columns=None))
meta[["spend", "link_click", "purchase"]] = meta[["spend", "link_click", "purchase"]].apply(pd.to_numeric)
assert meta["account_currency"].eq(CUR).all(), "Meta spend is in another currency"
print(meta[["campaign_name", "spend", "purchase"]])
# campaign_name spend purchase
# 0 Advantage+ | Homeware 1870.13 127
# 1 Prospecting | Candles 1912.18 168
# 2 Prospecting | Ceramics 1507.87 121
# 3 Retargeting | Basket 694.48 129
# 4 Retargeting | Viewed product 1070.51 157
print(round(meta["spend"].sum(), 2), meta["purchase"].sum())
# 7055.17 702
Two traps live here. Spend is reported in the ad account's currency, which is whatever was chosen when the account was opened, and an account opened in sterling or dollars years ago is common enough. The assert makes the notebook stop rather than add pounds to euro. And the 702 purchases are counted under Meta's attribution setting, the rule for how many days after a click or an ad view a purchase still counts. Write that setting into your notes next to the number, because the same campaigns give a different count under a different window.
Excel files: read the sheet, skip the decoration
read_excel works like read_csv with two additions: sheet_name picks the sheet, and it needs the openpyxl package for modern .xlsx files2. Excel stores numbers and dates as typed cells, so the number format problems of CSV disappear. The decoration does not: title blocks, merged headers, notes under the table.
Example: the newsletter report
news = pd.read_excel(EXPORTS / "newsletter_2025_06.xlsx", sheet_name="Campaigns", skiprows=3)
news["open_rate"] = news["Unique opens"] / news["Delivered"]
news["click_rate"] = news["Unique clicks"] / news["Delivered"]
print(news[["Campaign", "Delivered", "open_rate", "click_rate"]].round(3).head(3))
# Campaign Delivered open_rate click_rate
# 0 June edit 17979 0.608 0.030
# 1 New candles 18119 0.609 0.020
# 2 Ceramics restock 18081 0.582 0.027
print(news[["open_rate", "click_rate"]].mean().round(3))
# open_rate 0.586
# click_rate 0.026
print(news["Sent"].dtype)
# datetime64[ns]
The load is clean: the dates arrive as dates without a single parameter. The trap is in the meaning. An average open rate of 58.6% looks like a newsletter people love. Part of it is machines. Apple's Mail Privacy Protection downloads remote content, including the tracking pixel that counts an open, in the background when a message arrives, rather than when someone reads it8. Every Apple Mail user with the feature on "opens" every newsletter. Clicks need a person. For the question "does email pay back", Darragh uses the 2.6% click rate and the orders that GA4 attributes to email, and reports opens only as a deliverability signal.
GA4 in BigQuery: nested events, flattened in SQL first
The GA4 export to BigQuery writes one table per day, named events_YYYYMMDD, with one row per event4. Most of the interesting detail is nested. event_params is a repeated record: a list of key and value pairs, where the value sits in string_value, int_value or double_value depending on its type. ecommerce and the traffic source fields are records with fields inside them. And there are two clocks: event_timestamp is in microseconds, UTC, while event_date and the daily table names follow the property's time zone4.
The best place to flatten is BigQuery itself, before the data travels. A small subquery with UNNEST pulls one parameter out of the list, the pattern Google uses in its own example queries9. For the example shop it looks like this:
SELECT
event_date,
event_timestamp,
ecommerce.transaction_id AS transaction_id,
ecommerce.purchase_revenue AS revenue,
session_traffic_source_last_click.manual_campaign.medium AS medium,
(SELECT value.int_value FROM UNNEST(event_params)
WHERE key = 'ga_session_id') AS ga_session_id
FROM `ardmore-analytics.analytics_123456789.events_*`
WHERE _TABLE_SUFFIX BETWEEN '20250601' AND '20250630'
AND event_name = 'purchase'
The dataset is named after the GA4 property ID (analytics_ plus the number)4. _TABLE_SUFFIX picks the daily tables, which follow the property's time zone, so this query returns an Irish June, not a UTC June.
From Python there are two ways to run that query, both documented by Google10. The BigQuery client library is the direct one, and pandas_gbq is a thin wrapper. pandas itself used to have pd.read_gbq, deprecated since pandas 2.2 in favour of the pandas_gbq package6.
# needs: pip install "google-cloud-bigquery[bqstorage,pandas]" pandas-gbq
# and a login: gcloud auth application-default login
from google.cloud import bigquery
# sql holds the query above as a Python string
client = bigquery.Client(project="ardmore-analytics")
ga4_raw = client.query(sql).to_dataframe()
# or, the same in one line with pandas_gbq
import pandas_gbq
ga4_raw = pandas_gbq.read_gbq(sql, project_id="ardmore-analytics", dialect="standard")
I could not run these two lines for this article, because they need a real Google Cloud project with a GA4 export. Everything else in the chapter runs as shown. If the shop's orders also go to BigQuery, the article on BigQuery for a Rails and Solidus shop shows that side, and then the join can happen in SQL too.
Example: flattening the GA4 events in pandas
Sometimes the nested data arrives in Python anyway: a JSON export, a colleague's query with SELECT *. Then pandas does the flattening. First the nested records become columns:
with open(EXPORTS / "ga4_purchases_2025_06.jsonl", encoding="utf-8") as f:
records = [json.loads(line) for line in f]
ga = pd.json_normalize(records, sep="_")
print(len(ga))
# 3091
print(ga.columns.tolist())
# ['event_date', 'event_timestamp', 'event_name', 'event_params',
# 'session_traffic_source_last_click_manual_campaign_source',
# 'session_traffic_source_last_click_manual_campaign_medium',
# 'ecommerce_transaction_id', 'ecommerce_purchase_revenue']
json_normalize flattened the records but left event_params alone, because it is a list. explode gives each list element its own row, a second json_normalize opens the key and value pairs, and a pivot puts each key in its own column:
ga["row"] = range(len(ga))
params = ga[["row", "event_params"]].explode("event_params", ignore_index=True)
flat = pd.json_normalize(params["event_params"].tolist())
flat["row"] = params["row"]
flat["value"] = flat["value.string_value"].fillna(
flat["value.int_value"].astype("Int64").astype("string"))
wide = flat.pivot(index="row", columns="key", values="value")
print(wide.head(2))
# key ga_session_id page_location
# row
# 0 1748738047 https://ardmorehome.example/checkout/thanks
# 1 1748738111 https://ardmorehome.example/checkout/thanks
That is a lot of machinery for two parameters, which is the argument for doing it in SQL. Now the tidy table, with both clocks handled and the duplicates removed:
ga4 = pd.DataFrame({
"event_time": pd.to_datetime(ga["event_timestamp"], unit="us", utc=True).dt.tz_convert(TZ),
"event_date": pd.to_datetime(ga["event_date"], format="%Y%m%d"),
"transaction_id": ga["ecommerce_transaction_id"].astype("string"),
"revenue": ga["ecommerce_purchase_revenue"],
"medium": ga["session_traffic_source_last_click_manual_campaign_medium"],
})
print("duplicates:", ga4["transaction_id"].duplicated().sum())
# duplicates: 41
ga4 = ga4.drop_duplicates("transaction_id")
print(len(ga4), round(len(ga4) / len(real_orders), 3))
# 3050 0.77
print(ga4["medium"].value_counts())
# organic 953
# cpc 735
# paid_social 504
# (none) 368
# email 347
# referral 143
41 purchases were recorded twice, from reloaded thank you pages. Without drop_duplicates, GA4 revenue would be overstated by those orders. After it, GA4 holds 3,050 purchases, 77% of the shop's 3,960 real orders.
Coverage: how much of reality each source sees
That 77% deserves a name and a formula, because it is the number that tells you how far to trust any channel split from GA4. I call it coverage:
where is coverage, is the number of distinct purchases GA4 recorded after removing duplicates, and is the number of real orders in the shop export after removing test and staff orders and refund rows. It is a simple ratio of two counts (Foundations: ratios and rates).
The missing 23% are not random noise. They are mostly visitors who declined analytics consent or block the tag, which the article on event tracking and consent mode explains. If those visitors arrive through some channels more than others, GA4's channel shares are tilted, and no amount of pandas fixes that. What pandas does is make the coverage visible every month, so a sudden drop (a broken tag, a new consent banner) shows up before anyone acts on a channel report.
Example: four counts of the same June
The ad platforms and GA4 also disagree on the channels they share. Google Ads claims 1,162 conversions where GA4 credits paid search (medium cpc) with 735 purchases on a last click basis. Meta claims 702 purchases where GA4 credits paid social with 504.
Neither column is wrong. The platforms count every purchase their ads touched within their windows, including purchases another channel also touched. GA4 gives each purchase to one session's source. That is why the platform numbers can never be added up: Google's 1,162 plus Meta's 702 plus GA4's email and organic purchases would come to more orders than the shop ever had. The loading job is to keep each count in its own clearly named column. Deciding which one answers Darragh's budget question is the analysis, and the UTM tracking guide covers how to make GA4's side of it trustworthy in the first place.
Databases: SQL through SQLAlchemy into read_sql
When the data lives in a database, the shop's own or a warehouse, you do not export at all. You send a query and get a DataFrame back. pandas' read_sql takes the query and a connection, and SQLAlchemy builds that connection for almost any database from one URL11.
Three habits keep this safe and correct. Write the query with text() and named parameters (:since) instead of pasting values into the string, which protects against SQL injection and quoting errors. Keep the password out of the notebook, in an environment variable. And select only the columns you need, which is both faster and better data protection.
Example: customers who first ordered this year
query = text("""
SELECT customer_id, first_order, marketing_opt_in
FROM customers
WHERE first_order >= :since
""")
new_customers = pd.read_sql(query, engine, params={"since": "2025-01-01"},
parse_dates=["first_order"], dtype={"customer_id": "string"})
print(len(new_customers))
# 2317
print(new_customers.dtypes)
# customer_id string[python]
# first_order datetime64[ns]
# marketing_opt_in int64
2,317 customers placed their first order in 2025. And a quiet trap: marketing_opt_in went in as true or false and came out as 1 or 0, because SQLite has no Boolean type and stores integers. Other databases have their own versions of this (decimals that arrive as text, time zones dropped on the way). Check dtypes after every query, and convert:
new_customers["marketing_opt_in"] = new_customers["marketing_opt_in"].astype(bool)
print(round(new_customers["marketing_opt_in"].mean(), 3))
# 0.617
For a real database only the engine line changes, for example create_engine(os.environ["SHOP_DB_URL"]) with a URL such as postgresql+psycopg://reader@db.ardmorehome.example/shop stored outside the code. Use a read only database user for analysis. Then a mistake in a query can never change the shop.
Google Sheets: the budget that lives in a browser
Small businesses plan in shared sheets: the monthly budget per channel, the campaign calendar. The gspread package reads them through Google's API with a service account, a robot Google account whose key file you keep private and with which you share the sheet like with a colleague12.
Example: next month's budget sheet
# needs: pip install gspread, a service account key file,
# and the sheet shared with the service account's email address
import gspread
gc = gspread.service_account(filename="service_account.json")
ws = gc.open_by_key("YOUR_SHEET_KEY").worksheet("Budget July")
budget = pd.DataFrame(ws.get_all_records())
budget["Budget"] = pd.to_numeric(budget["Budget"].astype(str).str.replace(",", ""))
Like the BigQuery lines, this block needs a real account, so I have not run it here. The last line is the sheet trap: people type "1,500" into a cell formatted as text, and the value arrives as a string. Run the handshake on sheets too: rows and the budget total against what the sheet shows.
Parquet: save the clean result once
CSV is a fine way to receive data and a poor way to keep it. Every read repeats every guess. Parquet is a column based file format that stores the data together with its types13. pandas writes and reads it with pyarrow. After the handshake, save the clean table as Parquet, and every later notebook starts from the checked version instead of the raw export.
Example: the clean June orders
keep = sales[["order_id", "created_at", "customer_id", "type", "total"]]
keep.to_parquet(EXPORTS / "orders_2025_06.parquet", index=False)
back = pd.read_parquet(EXPORTS / "orders_2025_06.parquet")
print(back.dtypes)
# order_id string[python]
# created_at datetime64[ns, Europe/Dublin]
# customer_id string[python]
# type object
# total float64
print(os.path.getsize(EXPORTS / "orders_2025_06.csv"),
os.path.getsize(EXPORTS / "orders_2025_06.parquet"))
# 399631 111127
The string IDs stay strings, the timestamps keep their Dublin time zone, and the file is about a quarter of the CSV's size. No parameters needed on the way back in, because nothing is left to guess.
Personal data: load less, and pseudonymise what you keep
Shop exports contain personal data: names, email addresses, delivery addresses with Eircodes, sometimes phone numbers. The GDPR's data minimisation principle asks that personal data be "adequate, relevant and limited to what is necessary" for the purpose (Article 5(1)(c))14, and the Data Protection Commission (DPC) has guidance on anonymisation and pseudonymisation for Irish organisations15. For marketing analysis, the purpose almost never needs an email address. It needs to know that two orders came from the same customer.
Two tools cover most of it. The first is the column you never load: usecols in read_csv keeps the email column out of memory altogether, which is minimisation in one parameter. The second is pseudonymisation: replacing the identifier with a code that is the same for the same customer, but cannot be turned back into the customer without a separate secret (Article 4(5))14. A keyed hash (HMAC) does exactly that, and Python ships it in the standard library16.
Be clear about what pseudonymisation is not. It is not anonymisation. Recital 26 of the GDPR is plain that pseudonymised data is still information about an identifiable person14, and your business holds the secret. It lowers the risk, for example when a notebook is shared or a laptop is lost. It does not take the data out of the law. This is general information, not legal advice. For your own situation, read the DPC's guidance or ask someone qualified.
Example: an analysis table without names or emails
# keep the email column out of memory from the start
slim = pd.read_csv(EXPORTS / "orders_2025_06.csv", encoding="utf-8-sig", thousands=",",
usecols=lambda c: c not in {"Email", "First item"},
dtype={"Customer ID": "string"})
print(slim.columns.tolist())
# ['Order ID', 'Created at (UTC)', 'Customer ID', 'Type', 'Tags', 'Discount code', 'Total', 'Currency']
And for the table Darragh already loaded, a pseudonym replaces the customer ID. The secret lives in an environment variable, never in the notebook:
import hashlib
import hmac
SECRET = os.environ["PSEUDO_KEY"].encode() # kept outside the notebook
def pseudonymise(value: str) -> str:
"""The same customer always gets the same key, nobody can reverse it without SECRET."""
return hmac.new(SECRET, value.encode("utf-8"), hashlib.sha256).hexdigest()[:16]
analysis = (sales.drop(columns=["email"])
.assign(customer_key=sales["customer_id"].map(pseudonymise))
.drop(columns=["customer_id"]))
print(analysis.columns.tolist())
# ['order_id', 'created_at_utc', 'type', 'tags', 'discount_code', 'first_item',
# 'total', 'currency', 'created_at', 'customer_key']
Repeat customers are still visible (same key, many orders), joins between exports still work if every export is pseudonymised with the same secret, and nobody reading the notebook sees a single email address. Why a plain hash without a secret is not enough: email addresses are guessable, and anyone can hash a list of guesses and compare.
What came in, and what stayed
Every source has now gone through the checklist. The picture of rows loaded and rows kept is a useful summary for the notebook's first page, because it shows at a glance where the cleaning happened.
Example: rows per source for June
loaded = {"Shop orders": len(orders), "GA4 purchases": len(ga), "Google Ads": len(gads_raw),
"Meta": len(meta), "Newsletter": len(news), "Database": len(new_customers)}
kept = {"Shop orders": len(sales), "GA4 purchases": len(ga4), "Google Ads": len(gads),
"Meta": len(meta), "Newsletter": len(news), "Database": len(new_customers)}
print(pd.DataFrame({"loaded": loaded, "kept": kept}))
# loaded kept
# Shop orders 4090 4054
# GA4 purchases 3091 3050
# Google Ads 11 7
# Meta 5 5
# Newsletter 8 8
# Database 2317 2317
The small sources look empty on this scale, and that is honest: their trap was never volume. The Google Ads file lost only four rows, and those four rows were worth €21,393.12 of phantom spend. Whether a bar chart or a table serves this summary better is a fair question, and the article on exploring data with charts is the right companion for looking at freshly loaded data before you present anything.
My view
My view: write one small loading function per source, and treat it as the most important code in the project. Each function reads one export with every parameter spelled out, removes that source's known traps, runs the handshake as assert lines, and returns a tidy table with fixed column names, local time and no personal data it does not need. The tidy shape is Hadley Wickham's: each variable a column, each observation a row17. Everything downstream, the joins, the models, the charts, trusts these functions blindly, so they are where the care belongs.
I would also stop arguing about which source is "the truth". The shop export is the truth about orders and money. GA4 is a sample of the journey before the order, with a coverage you can measure. The ad platforms are each platform's own account of its contribution. Load all three, label them clearly, and let the analysis decide what each one is good for. The worst analyses I can imagine start by silently picking one source and pretending the others do not exist.
And I would keep the raw exports, untouched, next to the code. When a number is questioned in three months, the answer is to run the loader again on the original file. That only works if nobody "tidied up" the file in Excel.
Conclusion
Loading data looks like the boring part before the analysis. It is the part where most wrong numbers start. A CSV holds characters, not types, so every read is a set of decisions: separator, number format, encoding, types, dates. Write them down as parameters. Then prove the load with the handshake, rows, one money total and the date range against the source, before any chart.
Each source then brings its own trap. The shop export mixes tests, staff orders and refunds with sales and stores times in UTC. Google Ads adds title and totals rows. Meta sends numbers as text inside nested lists, in the account's currency, under its own attribution window. The newsletter's opens are inflated by machines. GA4 nests its parameters, keeps two clocks and sees only part of reality. Databases return their own types. Every one of these is a few lines of pandas once you know it is there.
The next chapter takes these tidy tables and cleans them properly: missing values, duplicates, types and text. If you would like a second pair of eyes on how your own exports come together, book the free workshop, and the first two weeks of work are on me.
