Data analysis · Beginner · 20 min
Move from spreadsheet formulas to pandas
By Padding · Updated 18 Nov 2026
Python 3.15 · pandas 3.1.1 · openpyxl 3.1.5 · uv 0.13 (checked on python:3.15-slim)
You will redo a shop's sales workbook in pandas 3.1, step by step, turning fill down, XLOOKUP, IF, filters, SUMIFS, COUNTIFS and a pivot table into a short Python script that writes its results back to Excel.
On this page
If you can write =XLOOKUP(...) or build a pivot table, you already know most of what pandas does. The ideas are the same: a table of rows and named columns, lookups against another table, totals by group. What changes is where the steps live. In a spreadsheet they are scattered across cells. In pandas they are lines in a script, run top to bottom, every time, on the whole column at once.
This tutorial takes a small phone-accessories shop with two branches and a workbook of sales. You will do the jobs you would normally do by hand in that workbook, one familiar move per step, and see the pandas line that replaces each formula. At the end, the script writes a fresh report workbook, so the people who read the numbers can keep using Excel or Google Sheets.
Everything happens in a throwaway folder, ~/shop-demo, which the last step removes.
Step 1 · Create the project and the sales workbook
Create the project and add pandas and openpyxl. pandas reads and writes .xlsx files through openpyxl, so it needs both. The version ranges allow bug-fix releases and nothing newer:
mkdir -p ~/shop-demo
cd ~/shop-demo
uv init --no-package --python 3.15
uv add "pandas>=3.1,<3.2" "openpyxl>=3.1,<3.2"Now make the workbook. In real life you would already have one. Here a short script builds it so you have the same data as this page. It has two sheets. sales holds one row per sale, typed in the way people often type at a till: the date only on the first sale of each day, with the rows below left blank. products is the price list.
cat > make_workbook.py <<'PY'
from datetime import date
from openpyxl import Workbook
wb = Workbook()
sales = wb.active
sales.title = "sales"
sales.append(["date", "branch", "sku", "qty", "payment"])
for row in [
(date(2026, 11, 2), "Central", "C-10", 3, "cash"),
(None, "Central", "S-20", 1, "mobile money"),
(None, "Market St", "C-10", 2, "card"),
(None, "Market St", "P-30", 1, "mobile money"),
(date(2026, 11, 3), "Central", "P-30", 2, "cash"),
(None, "Market St", "S-20", 4, "mobile money"),
(None, "Market St", "X-99", 1, "cash"),
(None, "Central", "C-10", 5, "mobile money"),
(date(2026, 11, 4), "Central", "S-20", 2, "card"),
(None, "Market St", "C-10", 1, "mobile money"),
(None, "Market St", "P-30", 3, "mobile money"),
(None, "Central", "P-30", 1, "cash"),
]:
sales.append(row)
products = wb.create_sheet("products")
products.append(["sku", "product", "category", "price"])
for row in [
("C-10", "Phone case", "Accessories", 25),
("S-20", "Screen protector", "Accessories", 15),
("P-30", "Power bank", "Power", 120),
("U-40", "USB-C cable", "Power", 20),
]:
products.append(row)
wb.save("shop.xlsx")
print("wrote shop.xlsx")
PY
uv run make_workbook.pyRead the sales sheet the way you would open the file and look at it:
cat > look.py <<'PY'
import pandas as pd
sales = pd.read_excel("shop.xlsx", sheet_name="sales")
print(sales.shape)
print(sales.head(4))
print(sales.dtypes)
PY
uv run look.pyA DataFrame is the sheet. sales.shape is the used range (rows, columns), not counting the header. The numbers on the left are the index, pandas' own row labels, which play the part of row numbers. Blank date cells come in as NaT, "not a time", pandas' empty value for dates.
Check it worked
wrote shop.xlsx appears, then (12, 5), then the first four sales. The first row has the date 2026-11-02, and the next three show NaT in the date column. The dtypes list shows date as a datetime64 type, qty as int64, and the text columns as str, the dedicated text type that pandas 3 uses by default. If you open shop.xlsx in Excel, LibreOffice or Google Sheets, you see the same two sheets.
Step 2 · Fill down the blank dates
In a spreadsheet you would select the date column, pick the blanks and fill each one from the cell above. In pandas that is one method on the column, ffill (forward fill). Put it in a small module, prepare.py, that the later steps build on, so the clean-up runs the same way every time:
cat > prepare.py <<'PY'
import pandas as pd
WORKBOOK = "shop.xlsx"
def load_sales():
sales = pd.read_excel(WORKBOOK, sheet_name="sales")
sales["date"] = sales["date"].ffill()
return sales
PY
cat > fill_down.py <<'PY'
import pandas as pd
from prepare import load_sales
raw = pd.read_excel("shop.xlsx", sheet_name="sales")
print("blank dates before:", int(raw["date"].isna().sum()))
sales = load_sales()
print("blank dates after:", int(sales["date"].isna().sum()))
print(sales["date"].value_counts().sort_index().to_string())
PY
uv run fill_down.pyTwo differences from the spreadsheet version are worth noticing. The source file is never changed: the fill happens each time the data is loaded. And ffill works on the whole column, so a new day of sales next week needs no extra dragging.
Fill down is only right when a blank really means "same as above". If a blank means "unknown", leave it empty and deal with it on purpose.
Check it worked
The script prints blank dates before: 9 and blank dates after: 0, then four sales on each of the three dates, 2026-11-02, 2026-11-03 and 2026-11-04.
Step 3 · Replace XLOOKUP with a merge
To get each sale's product name, category and price, a spreadsheet uses =XLOOKUP(C2, products!A:A, products!B:D) filled down the column. In pandas you join the two tables on their shared column, sku, with merge. how="left" keeps every sale, like a lookup does. indicator=True adds a _merge column saying whether each row found a match, the job #N/A does in a spreadsheet:
cat > lookup.py <<'PY'
import pandas as pd
from prepare import load_sales
sales = load_sales()
products = pd.read_excel("shop.xlsx", sheet_name="products")
merged = sales.merge(products, on="sku", how="left", indicator=True)
print(merged[["branch", "sku", "product", "price", "_merge"]].head(3))
print()
print("no match:")
print(merged.loc[merged["_merge"] == "left_only", ["date", "branch", "sku", "qty"]])
PY
uv run lookup.pyOne sale, at Market St on 3 November, has SKU X-99, which is not on the price list. In a spreadsheet that row would show #N/A and every total built on it would break or quietly skip it. Say the branch confirms it was a screen protector keyed in wrong. Fix it in one place, in code, and make the lookup fail loudly if anything else goes unmatched. Append this to prepare.py:
cat >> prepare.py <<'PY'
# Corrections confirmed with the branches. Keep each one, with a reason.
SKU_FIXES = {"X-99": "S-20"} # Market St, 3 Nov: screen protector keyed wrongly
def add_products(sales):
products = pd.read_excel(WORKBOOK, sheet_name="products")
sales = sales.assign(sku=sales["sku"].replace(SKU_FIXES))
merged = sales.merge(
products, on="sku", how="left", validate="many_to_one", indicator=True
)
missing = merged.loc[merged["_merge"] == "left_only", "sku"].unique()
if len(missing) > 0:
raise ValueError(f"SKUs not on the products sheet: {list(missing)}")
return merged.drop(columns="_merge")
PY
uv run python -c "from prepare import load_sales, add_products; s = add_products(load_sales()); print(len(s), 'rows,', int(s['price'].isna().sum()), 'without a price')"validate="many_to_one" checks that each SKU appears only once on the products sheet. If someone adds a duplicate row there, XLOOKUP would silently take the first match. pandas raises an error instead, and a join that grows your row count is one of the most common hidden bugs, so it is worth the extra argument. Join DataFrames in pandas without losing rows covers the other join types.
Check it worked
lookup.py prints the first three sales with their product name, price and both in the _merge column, then one unmatched row: Market St, X-99, quantity 1. The last command prints 12 rows, 0 without a price. Twelve rows in and twelve out means the lookup added columns without adding or dropping sales.
Step 4 · Turn IF and IFS into calculated columns
A calculated column in a spreadsheet is a formula in the first row, filled down. In pandas you write the calculation once, for the whole column. Three are useful here:
- Revenue,
=D2*H2in a sheet, isqty * price. - A 10% discount for three or more of an item,
=IF(D2>=3, I2*0.9, I2), isSeries.where. It keeps each value where the condition is true and uses the second argument everywhere else. Read it as "keep revenue where qty is under 3, otherwise take 90%". - An order size label with several bands,
=IFS(D2>=4, "bulk", D2>=2, "multi", TRUE, "single"), isSeries.case_when. Like IFS, the first condition that matches wins, so put the bands from highest to lowest.
Append these to prepare.py, with a prepared() function that runs every step in order:
cat >> prepare.py <<'PY'
def add_columns(sales):
revenue = sales["qty"] * sales["price"]
paid = revenue.where(sales["qty"] < 3, revenue * 0.9)
order_size = pd.Series("single", index=sales.index).case_when(
[
(sales["qty"] >= 4, "bulk"),
(sales["qty"] >= 2, "multi"),
]
)
return sales.assign(revenue=revenue, paid=paid, order_size=order_size)
def prepared():
return add_columns(add_products(load_sales()))
PY
cat > columns.py <<'PY'
from prepare import prepared
sales = prepared()
print(sales[["branch", "product", "qty", "revenue", "paid", "order_size"]].to_string())
print()
print("total paid:", sales["paid"].sum())
PY
uv run columns.pyassign returns a new table with the extra columns and leaves the one you passed in unchanged, so each function in prepare.py can be run and checked on its own.
Check it worked
Each sale now has revenue, paid and order_size. The first row, three phone cases at Central, shows revenue 75, paid 67.5 and multi. The row with five phone cases shows bulk and paid 112.5. Rows with one item show single and the same figure in revenue and paid. The last line is total paid: 1173.0.
Step 5 · Filter and sort instead of AutoFilter
AutoFilter hides the rows you do not want. In pandas you write the condition as a column of true and false values, a mask, and select the rows where it is true. Combine conditions with & (and) and | (or), with brackets round each one:
cat > filter_sort.py <<'PY'
from prepare import prepared
sales = prepared()
mask = (sales["branch"] == "Market St") & (sales["payment"] == "mobile money")
market_mobile = sales[mask].sort_values("paid", ascending=False)
print(market_mobile[["date", "product", "qty", "paid"]].to_string(index=False))
print()
big = sales.query("paid >= 100").sort_values(["branch", "paid"], ascending=[True, False])
print(big[["branch", "product", "paid"]].to_string(index=False))
PY
uv run filter_sort.pysort_values is the Sort dialog: one column or several, each ascending or descending. query takes the same condition as a short string, which reads well for simple filters. Neither changes sales itself. The filtered result is a new table, so there is no risk of forgetting a filter is switched on, which is a common cause of wrong totals in a shared sheet.
Check it worked
The first table lists the four Market St sales paid by mobile money, largest first: three power banks on 4 November at 324.0, one power bank on 2 November at 120.0, four screen protectors on 3 November at 54.0 and one phone case on 4 November at 25.0. The second lists the five sales of 100 or more: three at Central (240.0, 120.0, 112.5), then two at Market St (324.0, 120.0).
Step 6 · Replace SUMIFS and COUNTIFS with groupby
A single SUMIFS cell, such as "paid at Central for Power products", is a filter followed by .sum(). That works for one answer. When you would otherwise write the same SUMIFS in a column of cells, one per branch, use groupby: it splits the rows by a column, runs a calculation on each group and returns one row per group.
Named aggregation sets out the summary table the way you would set out the columns of a sheet: the new column's name, then the source column and the calculation. COUNTIFS with a condition becomes a sum of true and false values, since true counts as 1. The shop takes cash, card and mobile money, so count the mobile money sales per branch:
cat > totals.py <<'PY'
from prepare import prepared
sales = prepared()
# One SUMIFS cell: =SUMIFS(paid, branch, "Central", category, "Power")
one = sales.loc[(sales["branch"] == "Central") & (sales["category"] == "Power"), "paid"].sum()
print("Central, Power:", one)
print()
# A whole table of SUMIFS and COUNTIFS, one row per branch
by_branch = (
sales.assign(mobile=sales["payment"] == "mobile money")
.groupby("branch", as_index=False)
.agg(
sales=("sku", "count"),
items=("qty", "sum"),
paid=("paid", "sum"),
mobile_sales=("mobile", "sum"),
)
)
by_branch["mobile_share"] = (by_branch["mobile_sales"] / by_branch["sales"]).round(2)
print(by_branch.to_string(index=False))
PY
uv run totals.pyAdd a new branch to the workbook and it gets its own row the next time you run the script. In a sheet you would have to remember to add a SUMIFS row for it. Group and aggregate data in pandas goes further, with several keys, custom functions and transform.
Check it worked
The first line is Central, Power: 360.0. The table has one row per branch: Central with 6 sales, 14 items, 585.0 paid and 2 mobile money sales (share 0.33), and Market St with 6 sales, 12 items, 588.0 paid and 4 mobile money sales (0.67). The two paid figures add up to 1173.0, the total from the calculated-columns step. Checking that a breakdown adds back to the grand total is a habit worth keeping.
Step 7 · Build the pivot table with pivot_table
A pivot table puts one field down the rows, another across the columns and a summary in the cells. pivot_table takes the same four choices by name: index (rows), columns, values and aggfunc. fill_value=0 shows an empty combination as 0, and margins=True adds the grand totals row and column. Make a day column of plain dates first, so the row labels show no time of day:
cat > pivot.py <<'PY'
from prepare import prepared
sales = prepared()
sales = sales.assign(day=sales["date"].dt.date)
pivot = sales.pivot_table(
index="day",
columns="branch",
values="paid",
aggfunc="sum",
fill_value=0,
margins=True,
margins_name="Total",
)
print(pivot)
PY
uv run pivot.pyTo pivot by product category instead, change columns="branch" to columns="category". In a spreadsheet you would drag the field. Here you change one word, and the change is saved in the script for next month.
Check it worked
The pivot has a row for each of the three days and a Total row, and columns Central, Market St and Total. 3 November reads 352.5, 69.0 and 421.5. The Total row reads 585.0, 588.0 and 1173.0, matching the groupby table.
Step 8 · Write the results back to Excel and decide where each job belongs
Most people who use the numbers still want a workbook. ExcelWriter writes several DataFrames into one .xlsx file, one sheet each. Run the script whenever the sales sheet changes and the report is rebuilt from scratch, with nothing left over from last time:
cat > report.py <<'PY'
import pandas as pd
from prepare import prepared
sales = prepared()
by_branch = sales.groupby(["branch", "category"], as_index=False).agg(
items=("qty", "sum"),
paid=("paid", "sum"),
)
by_day = sales.assign(day=sales["date"].dt.date).pivot_table(
index="day",
columns="branch",
values="paid",
aggfunc="sum",
fill_value=0,
margins=True,
margins_name="Total",
)
with pd.ExcelWriter("report.xlsx", engine="openpyxl") as writer:
sales.to_excel(writer, sheet_name="sales", index=False)
by_branch.to_excel(writer, sheet_name="by branch", index=False)
by_day.to_excel(writer, sheet_name="by day")
for name, sheet in pd.read_excel("report.xlsx", sheet_name=None).items():
print(name, sheet.shape)
PY
uv run report.pyThe report holds values, not formulas, so anyone who opens it sees the same numbers. Keep shop.xlsx as the place where people type, and treat report.xlsx as output you can delete and rebuild. Automate a monthly Excel report with Python adds formatting, charts and a schedule.
pandas is not always the better tool. A rough guide:
- Keep it in the spreadsheet when people type data in, when the table is small and used once, when someone needs to try "what if" numbers by hand, or when the people who maintain it do not write code.
- Move it to pandas when you repeat the same clean-up every week or month, when the steps need to be checked or handed over, when files are joined or pasted together by hand, or when the data outgrows the sheet. An Excel worksheet stops at 1,048,576 rows and a Google Sheets file at 10 million cells, and both slow down well before that.
A script and an .xlsx file also work offline. If you pay for data by the bundle, or use a low-end Android phone to check Google Sheets on the move, running the heavy work on a laptop and sharing one small report file costs less than keeping a large shared sheet in sync.
When you have finished, remove the demo project. Python and uv stay installed:
cd ~
rm -rf ~/shop-demoCheck it worked
Before the clean-up, report.py prints three lines: sales (12, 11), by branch (4, 4) and by day (4, 4). Opening report.xlsx in a spreadsheet app shows the three sheets, with the pivot on by day and the same totals as before. After the clean-up, ls ~/shop-demo reports that the folder does not exist.
Next steps
- Read real workbooks with messy headers, several sheets and odd types: read Excel, CSV and Parquet files into pandas correctly.
- Do more with SUMIFS-style summaries: group and aggregate data in pandas.
- Catch lookups that lose or double rows: join DataFrames in pandas without losing rows.
- Turn
report.pyinto a scheduled job: automate a monthly Excel report with Python.
Part of these paths
Related tutorials
- Read Excel, CSV and Parquet files into pandas correctlyYou will load a semicolon-separated CSV with the wrong encoding, a multi-sheet Excel workbook whose headers start on row 4 and a Parquet file into pandas 3.1 with the right types, leading zeros and dates intact, reading only the columns you need.
- Group and aggregate data in pandasYou will summarise a shop's sales by region, month and city with pandas groupby, named aggregation, transform and filter, and finish with a regional report whose totals you have checked against the raw data.
- Join DataFrames in pandas without losing or duplicating rowsYou will join orders to customers and products with pandas merge, compare the four join types by row count, catch duplicate and mismatched keys with validate= and indicator=, list unmatched rows with an anti-join and stack new batches with concat.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials