pandas Series and DataFrames: the tables of Python, and ten shop questions answered with them

TL;DR

Difficulty: Beginner

A Series is one labelled column, a DataFrame a table of Series sharing one row index. Almost everything in pandas is selecting, filtering, calculating and summarising them.

  • Write the row sentence first: in a shop export one row is usually an order line, not an order. Counting rows overstated orders by 66% in the example.
  • pandas matches rows by label, not position. Missing labels become NaN, and sum() skips NaN silently: net revenue of €3.06 million came out as €69,000.
  • Change values only with one step loc, and switch copy on write on now: it is the only mode in pandas 3.0.
  • The worked example answers ten questions for an invented homeware shop and finds that paid social refunds 6.5% of its sales, twice any other channel.

Your shop export has 80,000 rows and someone wants revenue by channel, the average order value and the refund share. A spreadsheet can do it once. pandas does it in a few lines you can rerun next month. Here are the two objects behind everything in pandas, and ten everyday questions answered with them, each next to the spreadsheet way.

The question this chapter answers

You have an export from your shop. It opens in a spreadsheet, it has 80,000 rows, and somebody wants to know which channel brought in the most money last year, what the average order is worth and how much went back out as refunds. In a spreadsheet you would filter, sort, write a few SUMIF formulas and build a pivot table. It works, until next month, when you do it all again by hand and get a slightly different answer.

pandas is the Python library that does the same jobs in a few lines you can run again tomorrow, on next month's file, with the same result. It gives you two objects: the Series, one labelled column, and the DataFrame, a table of Series that share their row labels. Almost everything you will ever do in pandas is selecting, filtering, calculating with and summarising those two objects.

This chapter teaches them completely, from the first import to ten everyday business questions answered in code, each one next to the spreadsheet way you already know. It builds on the arrays from the chapter on NumPy: every pandas column is a NumPy array with a name and a set of labels attached. If you have not set up Python yet, the first chapter of this series does that, and the chapter on Python basics covers the lists, dictionaries and functions you will see here.

The structure follows chapter 5 of Wes McKinney's Python for Data Analysis1, the book by the person who created pandas, together with the official pandas documentation2. The book appeared in 2022, before pandas 2.0. Where pandas has moved on, I use the API as it stands today, pandas 2.3.1 (released on 7 July 2025)3, and say so.

If you only read one section

This part is for the person who commissions the analysis, reads the result and does not want to read code.

  • A DataFrame is a spreadsheet that remembers what you did. Every filter, every new column and every total is a line of code you can read, rerun and check. A spreadsheet keeps the result. pandas keeps the recipe.
  • Rows are matched by their label, not their position. That is the single biggest difference from a spreadsheet, it makes pandas safer for combining exports, and it produces one famous surprise: missing values (NaN) where you expected numbers. In the worked example below, that surprise silently turns a net revenue of €3.06 million into €69,000.
  • The first question is always "what is one row?" In the example shop's export, one row is one product line on an order, not one order. Count rows and you overstate orders by 66%.
  • The traps are in the business, not in the code. Test orders, staff orders, refunds stored as separate rows and timestamps in UTC instead of Irish time all sit in a normal shop export. Each one moves a number you would report. The code below finds all four.

If an analyst brings you a figure from pandas, ask two things: "What does one row of your table mean?" and "Which rows did you remove before you counted?" Good answers to those two questions are worth more than any chart.

Two habits that make every later number right

Before the mechanics, the idea I would put on the wall. Most mistakes in pandas, and in spreadsheets, come from two places: not knowing what a row is, and not knowing which rows are matched with which.

Habit one: write the row sentence. Before you compute anything, write one sentence that starts "One row is ...". "One row is one product line of one order, or one refund of such a line." If you cannot finish the sentence, you are not ready to count anything. Hadley Wickham's paper on tidy data makes the same point in general form: each variable a column, each observation a row, and each type of observational unit its own table4. Shop exports rarely arrive like that, so the row sentence is your first check.

Habit two: trust the label, not the position. In a spreadsheet, row 7 is row 7. If you paste a column from another sheet and the rows are in a different order, the spreadsheet will not notice. pandas attaches a label to every row (the index) and matches rows by label in every calculation. That is why it is safer, and it is why it sometimes hands you NaN instead of a number: no matching label, no value.

Example: the row sentence for a refund

A customer of the example shop orders a throw and two mugs, then returns the throw. In the export this is four rows: three sale lines on the order and one refund line with a negative amount, dated later. The row sentence ("one row is one product line or one refund line") tells you at once that the number of orders is not the number of rows, and that a sum of the amount column is already net of refunds. Without the sentence, both mistakes are easy: you would count four "orders" and, if you filtered to sale rows to count orders, forget that the refund is gone from your revenue total.

The example: Ardmore Home's order export

The example business is invented. Ardmore Home is an online homeware shop in Sligo (ardmorehome.example) selling candles, ceramics and textiles. Áine founded it. Darragh is the analyst. The shop has about 1,200 products and takes about 48,000 orders a year from about 21,000 customers, at an average order value of €66 and a gross margin of 52%. Customers arrive through organic search, paid search (Google Ads), paid social (Meta ads), the newsletter, direct visits and referrals. Darragh's standing question from Áine is always the same: "Which channel really pays back, and what should we do with next month's budget?"

This chapter does not answer the budget question yet. It does the groundwork: getting reliable totals per channel out of the shop's order export. Loading the real file is the job of the next chapter, so here the export is generated in code with a fixed seed, exactly as the NumPy chapter generated a year of orders. Copy the blocks in order into a notebook and you will get the same numbers I show.

Example: generating the export, traps included

First the imports, and one setting I recommend for every new project in 2025 (more on it in the section on copying):

import numpy as np
import pandas as pd

# Behave like pandas 3.0 already: every selection acts as a copy
pd.options.mode.copy_on_write = True
print(pd.__version__)   # 2.3.1

Now the export. It has one row per order line, 48,000 orders across 2024, staff and test orders mixed in, about 6% of orders partly refunded (11% of paid social orders, because that channel brings more impulse buys back), refunds as separate negative rows, and order times stored in UTC, as most shop systems store them.

rng = np.random.default_rng(2025)   # fixed seed: same data every run
TZ = "Europe/Dublin"                 # the shop's own time zone
DOMAIN = "ardmorehome.example"

# The catalogue: 1,200 products in three categories
n_products = 1_200
category = rng.choice(["candles", "ceramics", "textiles"], size=n_products, p=[0.35, 0.38, 0.27])
base_price = pd.Series(category).map({"candles": 22, "ceramics": 35, "textiles": 46.5}).to_numpy()
unit_price = np.round(base_price * rng.lognormal(0, 0.3, n_products)) - 0.01
popularity = 1 / np.arange(1, n_products + 1) ** 0.6   # a few bestsellers, a long tail
popularity = popularity / popularity.sum()

# 48,000 orders in 2024 from a pool of customers
n_orders = 48_000
channel = rng.choice(
    ["organic search", "paid search", "paid social", "email", "direct", "referral"],
    size=n_orders, p=[0.27, 0.22, 0.16, 0.14, 0.15, 0.06])
customer_id = rng.integers(1, 24_501, size=n_orders)
email = np.array([f"c{c:05d}@mail.example" for c in customer_id], dtype=object)
hour_weights = np.array([1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 5, 6, 6, 5, 5, 5, 5, 6, 7, 8, 8, 7, 5, 3])
local_time = (pd.Timestamp("2024-01-01")
              + pd.to_timedelta(rng.integers(0, 366, n_orders), unit="D")
              + pd.to_timedelta(rng.choice(24, n_orders, p=hour_weights / hour_weights.sum()), unit="h")
              + pd.to_timedelta(rng.integers(0, 60, n_orders), unit="min"))
# The shop records order time in UTC, not in Irish time
created_utc = (pd.Series(local_time)
               .dt.tz_localize(TZ, ambiguous=np.zeros(n_orders, dtype=bool), nonexistent="shift_forward")
               .dt.tz_convert("UTC"))

# Staff orders and test orders hide among the real ones
email[rng.choice(n_orders, 160, replace=False)] = f"staff@{DOMAIN}"
email[rng.choice(n_orders, 25, replace=False)] = f"test@{DOMAIN}"

orders = pd.DataFrame({"order_id": np.arange(100_001, 100_001 + n_orders),
                       "created_at": created_utc, "email": email, "channel": channel})

# Each order has one or more lines
n_lines = 1 + rng.poisson(0.6, n_orders)
lines = orders.loc[orders.index.repeat(n_lines)].reset_index(drop=True)
lines["line"] = lines.groupby("order_id").cumcount() + 1
pick = rng.choice(n_products, len(lines), p=popularity)
lines["sku"] = [f"AH{i + 1:04d}" for i in pick]
lines["category"] = category[pick]
lines["quantity"] = rng.choice([1, 2, 3], len(lines), p=[0.86, 0.11, 0.03])
lines["unit_price"] = unit_price[pick]
lines.loc[lines["email"] == f"test@{DOMAIN}", "unit_price"] = 1.00   # test orders at €1
lines["amount"] = (lines["quantity"] * lines["unit_price"]).round(2)
lines["type"] = "sale"

# Refunds: the first line of some orders comes back, as a separate negative row
refund_rate = pd.Series(channel).map({"paid social": 0.11}).fillna(0.05).to_numpy()
refunded = np.flatnonzero(rng.random(n_orders) < refund_rate)
first_lines = lines.index[lines["line"] == 1]
refunds = lines.loc[first_lines[refunded]]
refunds["created_at"] = refunds["created_at"] + pd.to_timedelta(rng.integers(3, 21, len(refunds)), unit="D")
refunds["amount"] = -refunds["amount"]
refunds["type"] = "refund"

export = (pd.concat([lines, refunds], ignore_index=True)
          .sort_values(["created_at", "order_id", "line"], ignore_index=True))
export = export[["order_id", "line", "created_at", "email", "channel", "sku",
                 "category", "quantity", "unit_price", "amount", "type"]]

No bother if you do not follow every line of the generator yet. Several of its tools (map, loc, concat, groupby) are what the rest of this chapter and the next few explain. What matters is the result: a table like the one your shop system would give you, with the traps a real export has. The email addresses are placeholders. A real export holds personal data, and the chapter on loading data covers what to keep and what to drop before analysis.

A Series is one labelled column

A Series is a one dimensional array of values with a label for each value. The labels are the index. If you know NumPy, a Series is a NumPy array plus an index plus a name. If you know spreadsheets, it is one column together with the row headings on its left, where the row headings can be anything you like (order numbers, product codes, dates), not just 1, 2, 3.

Two things make it more than a list. You can look values up by label, like a dictionary. And every calculation keeps the labels attached, so the result still knows which value belongs to which row.

Example: three prices with names

prices = pd.Series([18.99, 28.99, 38.99],
                   index=["candle", "vase", "throw"], name="price")
prices["vase"]          # 28.99, looked up by label
prices * 1.23           # every price with 23% VAT added, labels kept
# candle    23.3577
# vase      35.6577
# throw     47.9577
# Name: price, dtype: float64

Multiplying by 1.23 touched every value at once, with no loop: that is the vectorisation from the NumPy chapter. What is new is the left hand column. It travelled with the result. Hold on to that, because it is the source of both the safety and the NaN surprise later on.

Every column of a DataFrame is a Series. export["amount"] is a Series of 79,526 amounts, labelled with the row numbers 0 to 79,525.

A DataFrame is a table of Series sharing one index

A DataFrame is a two dimensional table: rows and columns, where each column is a Series and all columns share the same row index. Each column has one data type. Different columns can have different types. That is the structure McKinney describes as a dict of Series sharing one index1, and the pandas guide to its data structures puts it the same way2.

Three commands tell you most of what you need about any DataFrame you meet: shape (how many rows and columns), head() (the first few rows) and dtypes (the type of each column). Run them every time you load something new. It takes two seconds, and it is your first chance to write the row sentence.

Example: first look at the export

export.shape
# (79526, 11)

export.head(3)
#    order_id  line                created_at                email         channel     sku  category  quantity  unit_price  amount  type
# 0    134714     1 2024-01-01 00:00:00+00:00  c17725@mail.example  organic search  AH0136  ceramics         1       28.99   28.99  sale
# 1    134714     2 2024-01-01 00:00:00+00:00  c17725@mail.example  organic search  AH0328   candles         1       13.99   13.99  sale
# 2    127660     1 2024-01-01 00:41:00+00:00  c18186@mail.example        referral  AH0676   candles         1       21.99   21.99  sale

79,526 rows and 11 columns. The first two rows share an order number, 134714. That settles the row sentence: one row is one line of an order (or one refund of a line), and orders are spread over several rows. The left hand column (0, 1, 2) is the index. Here it is simply the row number, because nothing better identified a row on its own: an order number repeats and a line number repeats, only the pair is unique.

Data types: what pandas thinks each column is

Every column has a dtype, the data type pandas stores it as. It decides what you can do with the column: you can add up float64, you can extract the hour from a datetime, you cannot do either with text. A wrong dtype is the commonest silent error in imported data. A number stored as text sorts "100" before "20" and refuses to add up.

Example: the export's dtypes

export.dtypes
# order_id                    int64
# line                        int64
# created_at    datetime64[ns, UTC]
# email                      object
# channel                    object
# sku                        object
# category                   object
# quantity                    int64
# unit_price                float64
# amount                    float64
# type                       object

Whole numbers are int64, money is float64, the timestamp is a datetime that knows it is in UTC, and text is object. That last one is changing. In pandas 2.x, text columns are stored as object, a general container for any Python value. The pandas 2.3 release notes announce that pandas 3.0 will switch on a dedicated string type by default, shown as str, and you can try it today with pd.options.future.infer_string = True5. For the code in this chapter nothing changes. If you ever write if df["email"].dtype == object, that check will break in 3.0, so test for text with pd.api.types.is_string_dtype instead.

Two more columns deserve a better type. order_id is a number, but nobody adds up order numbers. It is an identifier. Keep it as int64 for now (it sorts and matches correctly), and never sum it. channel and category have only a handful of distinct values each, which is what the category dtype is for: it stores each distinct value once and saves memory. The chapter on cleaning data goes into types properly.

Selecting columns: square brackets

To take one column out of a DataFrame, put its name in square brackets: export["amount"] gives a Series. To take several, put a list of names in the brackets: export[["order_id", "amount"]] gives a smaller DataFrame. Note the two pairs of brackets: the outer pair selects, the inner pair is a Python list.

You will see export.amount in older tutorials. It works for simple names, but not for names with spaces, not for names that clash with a method (a column called count or type), and never for creating a new column. Square brackets always work, so use them.

Example: the money columns only

money = export[["order_id", "type", "amount"]]
money.head(2)
#    order_id  type  amount
# 0    134714  sale   28.99
# 1    134714  sale   13.99

That is the spreadsheet's "hide the other columns", except that nothing is hidden. money is a new, smaller table, and export is untouched.

Selecting rows and columns: loc by label, iloc by position

Square brackets are for columns. For rows, and for rows and columns together, pandas has two selectors:

  • loc selects by label: index labels for the rows, column names for the columns. export.loc[0:2, ["order_id", "amount"]] means "rows labelled 0 to 2, those two columns". With labels, the end of a slice is included.
  • iloc selects by integer position, exactly like Python lists and NumPy arrays. export.iloc[0:2, [0, 9]] means "the first two rows, the first and the tenth column". With positions, the end of a slice is excluded.

The pandas indexing guide spells out both rules6. The difference in slice ends is the part people trip over, and it trips them because the default index happens to look like positions. In the export, label 2 and position 2 are the same row. After you filter or sort, they no longer are.

loc also takes a condition instead of labels for the rows, which is the next section and the one you will use most.

Tap or click to enlarge

Example: the same two rows, two ways

export.loc[0:2, ["order_id", "amount"]]    # labels 0, 1 AND 2
#    order_id  amount
# 0    134714   28.99
# 1    134714   13.99
# 2    127660   21.99

export.iloc[0:2, [0, 9]]                    # positions 0 and 1 only
#    order_id  amount
# 0    134714   28.99
# 1    134714   13.99

Same table, same looking slice, three rows from loc and two from iloc. In a spreadsheet the closest thing to loc is a named range and the closest thing to iloc is INDEX(range, row, column). Neither shows you the difference this clearly, which is one reason spreadsheet ranges go wrong without anyone noticing.

Filtering rows with a condition

A comparison on a column gives a Series of True and False, one per row. pandas calls it a boolean mask. Put the mask inside square brackets (or in the row slot of loc) and you keep only the rows where it is True. This is the spreadsheet's AutoFilter, written down.

Combine conditions with & (and), | (or) and ~ (not), and wrap each condition in brackets, because Python evaluates & before ==. The plain words and and or do not work on a whole column and raise an error.

Example: questions 1 and 2, how many real orders are there?

The traps first. Ardmore's own email domain marks staff orders and test orders. Neither is a customer, both are in the export.

is_ours = export["email"].str.endswith("@" + DOMAIN)   # True for staff and test rows
export.loc[is_ours, "email"].value_counts()
# staff@ardmorehome.example    295
# test@ardmorehome.example      38

export.loc[is_ours, "order_id"].nunique()   # 185 orders

clean = export[~is_ours]                     # keep everything that is NOT ours
len(clean), clean["order_id"].nunique()
# (79193, 47815)

Question 1, how many orders? 47,815 real orders. Question 2, how many test and staff orders? 185, spread over 333 rows. The .str part gives you text methods for a whole column at once (endswith, contains, lower and so on).

Now look at what a careless count would have reported. len(export) is 79,526, which is 66% more than the true number of orders. Even export["order_id"].nunique() gives 48,000, including 185 orders that never earned a cent. The difference matters less than the habit: the row sentence told you that rows are not orders, so you counted unique order numbers, and the domain check told you which orders are not customers.

query: a filter you can read aloud

The same filter can be written as a sentence inside a string with query. Column names become variables, and and, or and not work as words7. For long filters it reads much better, and it is the version a manager can follow over your shoulder. Refer to a Python variable with @, for example query("amount > @threshold").

There are two limits. Column names with spaces need backticks inside the string (`unit price` > 20). And query reads columns, so derive anything you need (a month, an hour) as a column first. The next section shows how.

Example: splitting sale rows from refund rows

clean["type"].value_counts()
# sale      76422
# refund     2771

sales = clean.query("type == 'sale'")
refunds = clean.query("type == 'refund'")

76,422 sale lines and 2,771 refund lines. Read it aloud: "clean, where type equals sale". The boolean mask version, clean[clean["type"] == "sale"], does exactly the same. Use whichever reads better in context. I use masks when I need the mask again, and query when the filter is the point.

New columns, and chains you can read from top to bottom

You add a column by assigning to a new name: sales["margin"] = sales["amount"] * 0.52. That is the spreadsheet's "new column with a formula, filled down", except that there is nothing to fill down. The calculation applies to every row at once.

The alternative is assign, which returns a new DataFrame with the extra columns and leaves the original alone. Its advantage is that it fits into a method chain: a sequence of steps, one per line, wrapped in brackets, each step working on the result of the one before. A chain reads like the recipe it is: take the clean rows, keep the sales, add local time, add the hour, add the margin. Inside assign, write each new column as a lambda d: ..., a small function that receives the DataFrame as it is at that step, so a later column can use an earlier one.

Example: the UTC trap and the evening share

Áine wants to know how many orders come in during the evening, after 8pm, to time the newsletter. The export stores time in UTC. In winter Irish time equals UTC. From the end of March to the end of October Ireland is one hour ahead, so a summer order placed at 8.30pm in Sligo is stored as 19:30.

sales = (clean
         .query("type == 'sale'")
         .assign(created_local=lambda d: d["created_at"].dt.tz_convert(TZ),
                 hour_utc=lambda d: d["created_at"].dt.hour,
                 hour_local=lambda d: d["created_local"].dt.hour,
                 month_local=lambda d: d["created_local"].dt.month,
                 margin=lambda d: d["amount"] * 0.52))

one_per_order = sales.drop_duplicates("order_id")    # one row per order
(one_per_order["hour_utc"] >= 20).mean()     # 0.191
(one_per_order["hour_local"] >= 20).mean()   # 0.230

The mean of a column of True and False is the share of True, a useful trick. In UTC, 19.1% of orders arrive after 8pm. In Irish time, 23.0%. Four points of difference, purely from the clock, and for a shop selling into Germany or Austria, an hour further east, the gap is larger still. Any analysis by hour, by day or by month should convert to the shop's own time zone first. Daily totals around midnight and monthly totals on the last evening of a month shift in the same way. The chapter on time series goes deeper.

drop_duplicates("order_id") kept the first row of each order, so each order is counted once. Every order line carries the order's channel and time, so the first line is as good as any.

Sorting, counting and describing

Four methods answer most "show me" questions:

  • sort_values sorts by one or more columns, ascending=False for largest first. nlargest(n) is a shortcut for "the top n".
  • value_counts counts how often each value appears in a column, sorted from most to least. With normalize=True it gives shares instead of counts. In pandas 2.x the result is named count (or proportion), not after the column as it was in pandas 1.x.
  • describe gives count, mean, standard deviation, minimum, the quartiles and maximum of every numeric column in one call.
  • groupby splits the rows by a column, applies a calculation to each group and combines the results. It gets its own chapter later in this series. Here you only need its simplest form: df.groupby("channel")["amount"].sum(), "the sum of amount for each channel", the pandas version of a SUMIF or a one field pivot table.

Example: question 3, how many orders per channel?

one_per_order["channel"].value_counts()
# organic search    13135
# paid search       10594
# paid social        7600
# direct             7057
# email              6638
# referral           2791

one_per_order["channel"].value_counts(normalize=True).round(3)
# organic search    0.275
# paid search       0.222
# paid social       0.159
# direct            0.148
# email             0.139
# referral          0.058

Counted on orders, not rows. Organic search brings 27.5% of orders, paid search 22.2%, paid social 15.9%.

Example: question 4, gross revenue per channel

revenue = sales.groupby("channel")["amount"].sum().sort_values(ascending=False)
revenue
# organic search    873209.99
# paid search       704191.22
# paid social       514042.51
# direct            459588.71
# email             436810.37
# referral          183482.17
revenue.sum()   # 3171324.97
Bars of gross revenue before refunds by channel for the example shop, in thousands of euro. Organic search 873, paid search 704, paid social 514, direct 460, email 437, referral 183. Total 3,171 thousand euro from 47,815 orders. Tap or click to enlarge

€3.17 million gross across 47,815 orders. Sorted bars from largest to smallest are the right display for amounts across categories, as the data storytelling chapter on showing amounts and proportions argues. Gross is not the end of the story, though. Question 10 subtracts the refunds, and paid social moves.

Example: questions 5 and 6, average order value and a typical order

Average order value (AOV) is revenue divided by the number of orders:

AOV=RN\text{AOV} = \frac{R}{N}

where RR is the revenue in the period and NN is the number of orders in the same period, counted after removing test and staff orders. Revenue and orders must cover the same rows, or the ratio means nothing. Foundations: ratios and rates.

For Ardmore in 2024:

AOV=3,171,324.9747,815=66.32\text{AOV} = \frac{3{,}171{,}324.97}{47{,}815} = 66.32

Here R=3,171,324.97R = 3{,}171{,}324.97 euro of gross sales and N=47,815N = 47{,}815 orders, so AOV\text{AOV} is €66.32 per order.

In pandas, total per order first, then describe the totals:

order_totals = sales.groupby("order_id")["amount"].sum()   # one value per order
order_totals.describe().round(2)
# count    47815.00
# mean        66.32
# std         45.66
# min          9.99
# 25%         31.99
# 50%         53.99
# 75%         85.98
# max        499.92

Question 5: gross AOV is €66.32. Question 6: the typical order is smaller than the average. The median (the 50% line) is €53.99, and half of all orders fall between €31.99 and €85.98. The mean sits above the median because a minority of large orders pulls it up, the usual shape of order values. If Áine plans a free delivery threshold, the quartiles are more useful than the average. The Foundations section on the median explains why, and the data storytelling chapter on showing distributions shows how to chart this spread instead of hiding it behind one number.

Example: questions 7 and 8, top products and the largest orders

sales.groupby(["sku", "category"])["amount"].sum().nlargest(5)
# sku     category
# AH0001  textiles    154887.87
# AH0003  textiles     76488.75
# AH0004  textiles     73431.36
# AH0002  ceramics     41020.85
# AH0005  textiles     33241.25

order_totals.sort_values(ascending=False).head(3)
# order_id
# 143884    499.92
# 100204    433.94
# 115307    425.94

Question 7: one throw, AH0001, brings in €154,888, almost 5% of revenue on its own, and four of the top five products are textiles. Question 8: the largest order is €499.92. Looking at the largest orders is also a quality check. Had the test orders been priced at €9,999 instead of €1, they would be sitting at the top of this list, and sorting by size is often how you find them.

Example: question 9, December email orders over €100

Áine wants to know how many December newsletter orders were above €100, to judge a Christmas bundle. Months are taken from Irish time (the month_local column from the chain), totals per order come from groupby, and the filter is a query:

december_email = (sales
                  .query("channel == 'email' and month_local == 12")
                  .groupby("order_id")["amount"].sum())
len(december_email), int((december_email > 100).sum())
# (557, 94)

557 email orders in December, of which 94 (16.9%) were over €100. Notice the order of the steps: filter the lines, total them per order, then compare the order total with €100. Comparing line amounts with €100 would have answered a different question.

Arithmetic lines up by label, and missing labels become NaN

When you add, subtract, multiply or divide two Series, pandas does not pair the first value with the first value. It pairs equal labels. Labels that exist on only one side get a result of NaN, "not a number", pandas' marker for a missing value. McKinney calls this data alignment1, and the pandas guide on basic functionality covers the fix: the method versions of the operators (add, sub, mul, div) take a fill_value that stands in for the missing side8.

That alignment is a feature. Two exports in different orders still combine correctly, which a spreadsheet does not do. The surprise is what happens next: most pandas summaries skip NaN without telling you. sum() adds up whatever is there. So a NaN in the middle of your net revenue does not stop the total. It quietly removes rows from it.

Example: question 10, net revenue per order, and how it goes wrong

Darragh wants net revenue per order: gross sales minus refunds. He totals both per order and subtracts:

gross = sales.groupby("order_id")["amount"].sum()      # 47,815 orders
refund = refunds.groupby("order_id")["amount"].sum()   # 2,771 orders, negative

net_wrong = gross + refund
net_wrong.isna().sum()   # 45044 orders are NaN
net_wrong.sum()          # 69373.22

The refund Series only has labels for the 2,771 refunded orders. For the other 45,044 orders there is no matching label, so the result is NaN. And sum() skips them, so the "net revenue" comes out at €69,373: the net value of the refunded orders only. Nothing raised an error. A dashboard built on this would show a 98% collapse in revenue, or worse, a number small enough to look plausible for a single month.

The fix is to say what a missing refund means. It means zero:

net = gross.add(refund, fill_value=0)
net.sum()    # 3058547.76
net.mean()   # 63.97, the net average order value

Net revenue is €3,058,547.76 and net AOV €63.97. Now the refund share, the part of gross sales that went back out:

s=FGs = \frac{F}{G}

where ss is the refund share, FF is the total refunded (as a positive amount) and GG is gross sales over the same orders. Foundations: percentages.

s=112,777.213,171,324.97=0.0356s = \frac{112{,}777.21}{3{,}171{,}324.97} = 0.0356

With F=112,777.21F = 112{,}777.21 and G=3,171,324.97G = 3{,}171{,}324.97, s=3.56%s = 3.56\%, so 3.56% of gross sales went back as refunds. Per channel, with div lining the two totals up by channel name:

refund_share = (-refunds.groupby("channel")["amount"].sum()).div(
                sales.groupby("channel")["amount"].sum()).sort_values(ascending=False)
refund_share.round(3)
# paid social       0.065
# paid search       0.033
# email             0.030
# referral          0.029
# direct            0.029
# organic search    0.028
Bars of refunds as a percentage of gross sales by channel for the example shop. Paid social 6.5%, paid search 3.3%, email 3.0%, referral 2.9%, direct 2.9%, organic search 2.8%. Paid social refunds more than twice the share of any other channel. Tap or click to enlarge

Paid social refunds 6.5% of its gross sales, more than twice the rate of any other channel. That is the first real input for Áine's standing question: judged on gross revenue, paid social looks like the third best channel. Judged on what it keeps, it gives back more than any other, and that gap belongs in the budget discussion before any return on ad spend is calculated. The margin, the ad spend and the return come in later chapters. The point here is that the table told Darragh this in four lines, and that the version with NaN would have hidden it.

SettingWithCopyWarning, and why copy on write ends it

If you have used pandas before, you have probably met this warning: "A value is trying to be set on a copy of a slice from a DataFrame." It appears when you change values in something that might be a view of another table (sharing its memory) or might be a copy (independent of it). In pandas up to now, whether a selection was a view or a copy depended on internal details that were hard to predict, so a change might reach the original table or might not. The warning was pandas admitting it could not tell you which.

McKinney's book describes the old rule: a column taken from a DataFrame was a view, so changing it in place changed the DataFrame. That is exactly what is going away. Copy on write is a mode, available as an option since pandas 2.0, in which every selection behaves as a copy from the user's point of view. pandas only copies the data when one side is actually changed, so it costs little. The pandas 2.3 guide states that copy on write will be the default and only mode in pandas 3.0, and that "chained assignment will never work"9. The 2.3 release notes add that SettingWithCopyWarning will be removed, because the ambiguity it warned about will be gone5.

Chained assignment means two selections in a row followed by =, such as df[df["channel"] == "email"]["amount"] = 0. The first brackets make a new object, the second brackets select from that, and the assignment changes the new object, not df. The one step fix is always loc, with the row condition and the column in the same brackets.

Example: the same three lines, old mode and new mode

df = pd.DataFrame({"channel": ["email", "direct", "email"],
                   "amount": [40.0, 55.0, 70.0]})

# 1. Chained assignment: does not change df
df[df["channel"] == "email"]["amount"] = 0
# old mode: SettingWithCopyWarning
# copy on write: ChainedAssignmentError warning
df["amount"].tolist()      # [40.0, 55.0, 70.0], unchanged in both modes

# 2. Filter into a new table, then change the new table
email = df[df["channel"] == "email"]
email["amount"] = email["amount"] * 1.2
# old mode: SettingWithCopyWarning, copy on write: silent, and correct
df["amount"].tolist()      # [40.0, 55.0, 70.0], the original is untouched

# 3. One step with loc: changes df, in both modes, no warning
df.loc[df["channel"] == "email", "amount"] = 0
df["amount"].tolist()      # [0.0, 55.0, 0.0]

I ran all three in pandas 2.3.1 with copy on write switched off and switched on. Case 1 warns in both modes and changes nothing. Case 2 warned in the old mode although the code was correct, which is how a generation of analysts learned to ignore warnings. Under copy on write it is silent, because "a filtered table is its own table" is now simply true. Case 3 is the one to remember: when you want to change the original, select rows and columns in one loc and assign.

The rule that follows: if you want a separate table, filter into a new variable and change it freely. If you want to change the original, use df.loc[rows, columns] = value. Switch copy on write on at the top of every notebook now, as in the first block of this chapter, and the code you write today will behave the same when pandas 3.0 arrives.

Excel does X, pandas does Y

The pandas documentation has its own comparison with spreadsheets10. Here is the version for the ten questions of this chapter and the operations behind them, with the trap each one hides.

TaskIn a spreadsheetIn pandasThe trap
See the tableOpen the file and scrolldf.shape, df.head(), df.dtypesRows are not orders: write the row sentence
Keep some columnsHide columnsdf[["a", "b"]]None, the original is unchanged
Filter rowsAutoFilterdf[mask] or df.query("...")Filters in a spreadsheet are invisible to the next person
Count unique ordersUNIQUE then COUNTAdf["order_id"].nunique()Counting rows overstates orders
Count by categoryCOUNTIF or a pivot tabledf["channel"].value_counts()Count orders, not lines
Sum by categorySUMIF or a pivot tabledf.groupby("channel")["amount"].sum()Test and staff orders still inside
New column from a formulaFormula, filled downdf.assign(margin=...) or df["margin"] = ...A formula filled down one row short
SortSort A to Zdf.sort_values("amount", ascending=False)Sorting one column alone detaches it from its rows in a spreadsheet, never in pandas
Summary statisticsAVERAGE, MEDIAN, QUARTILEdf["amount"].describe()The average of lines is not the average order
Combine two lists by keyVLOOKUP or XLOOKUPArithmetic aligns on the index, merge joinsMissing keys become NaN, and sum() skips them
Change values in placeType over the celldf.loc[mask, "col"] = valueChained brackets change nothing

Two lines in that table carry most of the risk in practice. Sorting a single column in a spreadsheet without its neighbours detaches every value from its row. The spreadsheet asks once whether to expand the selection, and after one wrong click nothing warns you again. And a lookup that does not find its key returns an error you can paste over or a zero you cannot tell from a real zero. pandas makes the same situation visible as NaN, provided you look. That is why my code above checks isna().sum() before trusting a total.

The ten questions in one table

#QuestionpandasAnswer, Ardmore Home 2024
1How many real orders?clean["order_id"].nunique()47,815
2How many test and staff orders?export.loc[is_ours, "order_id"].nunique()185
3Orders per channel?value_counts() on one row per orderOrganic search 13,135 (27.5%)
4Gross revenue per channel?groupby("channel")["amount"].sum()Organic search €873,210, total €3,171,325
5Average order value?revenue divided by unique orders€66.32 gross, €63.97 net
6What is a typical order?describe() on order totalsMedian €53.99, middle half €31.99 to €85.98
7Top products?groupby(["sku", "category"]) and nlargestAH0001, a throw, €154,888
8Largest orders?sort_values(ascending=False)€499.92
9December email orders over €100?query, then groupby, then a comparison94 of 557
10Refund share?add and div with aligned labels3.56% overall, 6.5% for paid social

Each answer is one or two lines of code, and each line is readable by the next person, including you next month. That is the real gain over the spreadsheet: not speed (a pivot table is fast), but a recipe you can rerun on February's export with one change of file name, and check line by line when a number looks odd. The data storytelling chapter on tools and workflow for good charts makes the same argument for charts.

My view

My view: learn four things first and properly, and leave the rest of pandas until you need it. They are square brackets for columns, loc for everything that involves rows (selecting and changing), boolean masks or query for filters, and groupby with one function for totals. With those four you can answer most of the questions a shop owner asks, and every one of the traps in this chapter was found with them.

I would also make three things non negotiable from the first day. Switch copy on write on at the top of every notebook, so the warnings that taught people to ignore warnings never appear, and so your code is ready for pandas 3.0. Write the row sentence before the first total, in a comment at the top of the notebook. And never report a sum without having checked isna().sum() on the thing you summed: alignment is the best feature pandas has, and the one that will hurt you if you forget it exists.

Method chains are worth adopting early, but not at any price. A chain of five readable steps is clearer than five reassignments of the same variable. A chain of fifteen steps with clever lambdas is not. Break it where a manager reading over your shoulder would need to stop and ask a question.

And the comparison with spreadsheets is not a contest. A spreadsheet is grand, and still the fastest way to look at a few hundred rows once. The moment the same analysis has to be repeated, checked or handed over, the recipe beats the result. Data science and analytics work of this kind is a core part of what I do for clients, and in my data science work the client owns the code, the notebooks and the data at the end.

Conclusion

A Series is a labelled column, a DataFrame a table of Series sharing one index, and almost every task is selecting, filtering, calculating and summarising them. Select columns with square brackets, rows with loc by label or iloc by position, filter with masks or query, add columns with assign, and change the original only with one step loc. Write the row sentence first, remove what is not a customer, convert time to the shop's own zone, and check for NaN before you trust a total.

For Ardmore Home, that took 47,815 real orders out of 79,526 rows, put gross revenue at €3.17 million and net at €3.06 million, and showed that paid social returns 6.5% of its sales, twice the rate of any other channel. The next chapter loads the real exports, the shop CSV, GA4 from BigQuery, the ad platforms and the newsletter tool, each with its own trap, and the chapter after that cleans them. If you would rather have this set up for your own shop's data, the free workshop is where we look at your exports together.

If your shop's exports live in spreadsheets and the totals never quite agree, book the free workshop: we look at your real exports together and write the row sentence for each, and the first two weeks of work are on me.

Sources

  1. 1.

    Wes McKinney, Python for Data Analysis: Data Wrangling with pandas, NumPy, and Jupyter, 3rd edition, O'Reilly, 2022, chapter 5, Getting Started with pandas, open access edition, https://wesmckinney.com/book/pandas-basics

  2. 2.

    pandas development team, Intro to data structures, pandas 2.3 user guide, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/user_guide/dsintro.html

  3. 3.

    Python Package Index, pandas release history, version 2.3.1 released 7 July 2025, https://pypi.org/project/pandas/#history

  4. 4.

    Hadley Wickham, Tidy Data, Journal of Statistical Software, volume 59, issue 10, 2014, https://doi.org/10.18637/jss.v059.i10

  5. 5.

    pandas development team, What's new in 2.3.0 (June 4, 2025), pandas 2.3 release notes, https://pandas.pydata.org/pandas-docs/version/2.3/whatsnew/v2.3.0.html

  6. 6.

    pandas development team, Indexing and selecting data, pandas 2.3 user guide, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/user_guide/indexing.html

  7. 7.

    pandas development team, pandas.DataFrame.query, pandas 2.3 API reference, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/reference/api/pandas.DataFrame.query.html

  8. 8.

    pandas development team, Essential basic functionality: flexible binary operations, pandas 2.3 user guide, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/user_guide/basics.html

  9. 9.

    pandas development team, Copy on Write (CoW), pandas 2.3 user guide, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/user_guide/copy_on_write.html

  10. 10.

    pandas development team, Comparison with spreadsheets, pandas 2.3 getting started guide, 2025, https://pandas.pydata.org/pandas-docs/version/2.3/getting_started/comparison/comparison_with_spreadsheets.html

Shelter

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

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

Donate to Shelter