Working with pandas starts with knowing what to do with your data. Follow a practical example to clean order records, calculate sales totals, check your results, and prepare a simple report.
Pandas is a Python library for working with data arranged in rows and columns. You can use it to import files, clean records, filter information, calculate summaries, and prepare results for reporting.
The difficult part of a first analysis is often knowing which step comes next. This Python pandas tutorial follows one small orders dataset from an untidy CSV to a checked sales summary and a chart. You will see what each operation does and why it belongs in the workflow.
You need basic Python knowledge but no previous pandas experience. The example uses fictional data, with deliberate errors for practice.
Tested environment: Python 3.12.14 and pandas 2.2.3. The analysis and chart-generation code were executed together. Compatibility with other versions has not been tested.
What is pandas, and how is it used for data analysis?
Pandas provides tools for manipulating tabular data: the kind of information you might keep in a spreadsheet or database table. Its main table structure is called a DataFrame.
The official pandas introductory tutorials cover reading tables, selecting records, creating columns, summarising values, and plotting results.
For example, an order file might contain inconsistent category names, a repeated record, and a missing quantity. Pandas lets you identify those problems, apply documented corrections, and calculate totals from the records suitable for analysis.
Python supplies the programming language. Pandas supplies the table operations. Together, they let you express an analysis as code that you can inspect and repeat.
That does not make every result automatically correct. You still need to decide what each row represents, how missing information should be handled, and whether the output answers your question.
What you need before starting
You should be comfortable with variables, lists, dictionaries, and function calls. You also need to know how to run Python code.
For this guide, use Jupyter Notebook. If Python is already installed, run this command in your terminal:
python -m pip install pandas matplotlib notebook
Then launch Notebook:
python -m notebook
Create a Python notebook. In its first code cell, run:
import pandas as pd import matplotlib.pyplot as plt print(pd.__version__)
'pd' is a conventional short name for 'pandas'. Matplotlib supplies the plotting tools used later.
Check the pandas installation instructions if your environment needs a different installation route.
Run the remaining Python blocks in order. Keep the notebook and practice CSV in the same folder. If you have several Python environments, make sure the notebook uses the one where you installed the packages.
Understand DataFrames, Series, and indexes
A pandas DataFrame is a two-dimensional table with labelled rows and columns. A Series is a one-dimensional labelled structure, such as a selected column. The index contains row labels.
Here is a small illustration, separate from the main exercise:
example = pd.DataFrame({ "category": ["Home", "Stationery"], "quantity": [2, 3]})print(example)
|
Index |
category |
quantity |
|
0 |
Home |
2 |
|
1 |
Stationery |
3 |
The whole table is a DataFrame. Selecting example["quantity"] returns a Series.
Selecting an example ["[quantity]"] returns a one-column DataFrame: the inner brackets create a list of column names.
The default row labels are 0 and 1, but labels need not match row positions. Filtering a table can leave gaps in its index without causing an error.
Columns also have data types. Numbers, text, and dates behave differently, so checking types is part of preparing data for analysis.
The official table-orientated data tutorial illustrates these structures.
Step 1: Load the practice dataset
Our question is:
What is the sales value for each product category among orders with complete calculation fields?
In this fictional dataset, each row represents one order for one product category. Each legitimate order has a unique ID. Unit prices are in GBP. Tax, discounts, and refunds are outside the example.
Copy the following into a plain-text file named orders. csv. Preserve the spaces in category names: we will clean them later.
order_id,order_date,category,quantity,unit_price
1001, 2026-09-01, Stationery, 3, 12.50
1002, 2026-09-02, Accessories, 2, 25.00
1003, 2026-09-03, stationery, 5, 8.00
1004, 2026-09-04, Home, 1, 45.00
1005, 2026-09-05, Accessories, 4, 15.00
1006, 2026-09-06, Home, 30.00
1007, 2026-09-07, Stationery, 2, 10.00
1008, 2026-09-08, Home, 3, 20.00
1009, 2026-09-09, accessories, 1, 35.00
1010, 2026-09-10, Home, 2, 40.00
1003, 2026-09-03, stationery, 5, 8.00
Load it into pandas:
raw = pd.read_csv("orders.csv")print(raw. head())
read_csv() reads the file and creates a DataFrame. We call it raw because we want to retain the original imported records. Later transformations will use separate variables.
If the file cannot be found, check that it is named orders.csv, rather than orders. csv.txt, and is in the notebook’s working folder.
Step 2: Inspect the data before changing it
Start with a few checks:
print(raw.shape) raw.info() print(raw.isna().sum()) print(raw.duplicated().sum())
Each check answers a different question:
|
Check |
What it tells you |
Result in this example |
|
raw.shape |
Number of rows and columns |
11 rows, 5 columns |
|
raw.info() |
Column types and non-missing counts |
Dates are initially text; quantity contains a missing value. |
|
raw.isna().sum() |
Missing values per column |
One missing quantity |
|
raw.duplicated().sum() |
Exact repeated rows after the first occurrence |
One duplicate |
info() prints its own summary. Writing print (raw). info()) adds None after that summary because the method does not return a new table.
Check category labels too:
print(raw["category"].unique())
You will find differences in case and spacing. Without standardisation, pandas treats 'stationery' and 'stationery' as different labels.
These checks establish our cleaning plan. We will remove the confirmed repeated record, standardise categories, convert dates, and set aside the order whose quantity is unknown.
Step 3: Clean the data with clear rules
Remove the confirmed duplicate
Inspect all occurrences of repeated rows:
print(raw.loc[raw.duplicated(keep=False)])
The record for order 1003 appears twice with identical values. Because each legitimate order is unique in this practice dataset, we treat the second copy as accidental.
orders = raw.drop_duplicates().copy()print(len(orders))
There are now 10 rows. copy() gives us a separate working table while preserving raw.
In real sales data, one order may contain several line items. A repeated order ID alone would not establish that a row should be removed.
Standardise category labels
Remove surrounding spaces and apply consistent capitalisation:
orders["category"] = orders["category"].str.strip().str.title()print(orders["category"].unique())
The categories are now:
-
Stationery.
-
Accessories.
-
Home.
These transformations suit our simple labels. Real category names may require a controlled mapping, particularly when capitalisation carries meaning.
Handle the missing quantity
Order 1006 has a unit price but no quantity. Replacing the quantity with zero would assert that no units were ordered. The file does not support that conclusion.
Instead, separate records needing review from those suitable for the sales calculation:
required = ["quantity", "unit_price"]needs_review = orders. loc[ orders[required].isna().any(axis=1)]. copy()clean = orders. dropna(subset=required). copy()print("Needs review:", len(needs_review)) print("Ready for analysis:", len(clean))
The results are:
|
Status |
Records |
|
Needs review |
1 |
|
Ready for analysis |
9 |
Here, axis=1 checks across each row to find any missing required field.
The final sales summary excludes order 1006. It is not a complete total for all legitimate orders. Recovering its quantity could change the category comparison.
The official missing-data guide explains the available methods. The appropriate treatment depends on what the missing information means.
Convert dates and check the cleaned data
Convert the date strings using their known year-month-day format:
clean["order_date"] = pd.to_datetime(clean["order_date"], format="%Y-%m-%d", errors="raise")assert len(clean) == 9assert clean[required]. notna().all().all()assert clean["order_id"]. is_uniqueassert (clean["quantity"] > 0). all()assert (clean["unit_price"] >= 0). all()
An assert checks an assumption and raises an error if it fails. These conditions suit the supplied exercise; they are not a universal validation policy.
Returns, free products, or multi-line orders would need different rules.
errors="raise" stops processing if a date cannot be converted, making a problem visible rather than silently accepting it.
Step 4: Select and filter the records you need
Suppose you want to inspect stationery orders containing at least three units:
stationery_orders = clean.loc[
(clean["category"] == "Stationery") &
(clean["quantity"] >= 3),
["order_id", "quantity"]
]
print(stationery_orders.to_string(index=False))
|
order_id |
quantity |
|
1001 |
3.0 |
|
1003 |
5.0 |
Each condition produces True or False values. The & operator requires both conditions to be true.
Keep parentheses around each condition. Python’s ordinary oes not perform this element-by-element combination.
With .loc, the part before the comma selects rows, and the part after it selects columns. Here, we use conditions for rows and a list of column names.
.iloc selects by numerical position instead. For example, clean. iloc[0] returns the first row in the current table, whatever its index label.
The filtered result does not remove other records from the clean. We will still use all nine complete records for the category summary.
Step 5: Calculate and summarise sales
Calculate each order’s sales value
Multiply quantity by unit price:
clean["sales_value"] = clean["quantity"] * clean["unit_price"]print( clean[ ["order_id", "quantity", "unit_price", "sales_value"] ].head())
Order 1001 contains three units at £12.50 each, producing a sales value of £37.50. Pandas applies the calculation across the columns without requiring an explicit loop.
This measure is sales value before any tax, discounts, or refunds. It is not profit: the dataset contains no cost information.
Our small prices allow a straightforward demonstration. Production financial calculations need an appropriate precision and rounding policy.
Compare sales by category
Group the records by category, add their sales values, and sort the result:
summary = (clean.groupby("category", as_index=False)["sales_value"] .sum() .sort_values("sales_value", ascending=False))print(summary.to_string(index=False))
|
category |
sales_value |
|
Home |
185.0 |
|
Accessories |
145.0 |
|
Stationery |
97.5 |
groupby() forms groups using the category labels. Selecting sales_value identifies the measure, and sum() adds it within each group.
as_index=False keeps the category as an ordinary column.
Home has the highest sales value among the complete records: £185. That describes this sample, not a wider market trend.
Check the summary
The grouped totals should match the total of the underlying records:
import mathassert math. isclose( summary["sales_value"].sum(), clean["sales_value"].sum(), rel_tol=1e-9, abs_tol=1e-9)print(f"Included sales value: £{clean['sales_value'].sum():.2f}")
The result is £427.50, excluding the unresolved order.
math.isclose() allows a small tolerance when comparing floating-point calculations.
Step 6: Visualise and export the results
A bar chart makes the category comparison easy to scan:
axe = summary.plot.bar( x="category", y="sales_value", legend=False, color= "#256080", rot=0)ax.set( title=" Sales value by category: complete practice records", xlabel="Category", ylabel= "Sales value (GBP)" plt.tight_layout() plt.show()
Chart placement: Immediately after this code block.

Use the chart to communicate the same checked summary, rather than introducing a different calculation.
The official Pandas plotting tutorial explains plotting with its default Matplotlib backend.
Save the records and summary for later use:
clean.to_csv("orders_clean.csv", index=False)summary.to_csv("sales_summary.csv", index=False)needs_review.to_csv("orders_needing_review.csv", index=False)
index=False prevents pandas from writing its row labels as an extra CSV column.
These files are written to the current working folder. Existing files with the same names will be overwritten.
The review file preserves the incomplete order separately. CSV files do not retain pandas data-type information, so specify or check date types when reading exported records again.
Common pandas mistakes beginners should avoid
Cleaning before inspecting. Check the records first. An unexpected total might come from missing values, inconsistent categories, or the wrong interpretation of a row.
Using an incorrect column name. A KeyError often means the requested label does not exist. Inspect clean. columns; spaces and capitalisation matter.
Treating missing values as zero. That changes the meaning of the data. Document your rule and identify excluded records.
Using chained assignment. Update the intended DataFrame directly. For example, use:
df.loc[condition, "column"] = value
This is a general syntax illustration; 'df', 'condition', and 'value' must be defined for your own task.
The official copy-on-write guidance explains why chained assignment does not work under pandas 3.0’s copy-on-write rules.
Running notebook cells out of order. A later cell may depend on a variable created earlier. Restart the kernel and run the complete notebook from the beginning before relying on its results.
Assuming an unchanged index is broken. Filtering can leave gaps in labels. Reset the index only when your next task needs it.
Practise the workflow and choose your next step
Repeat the exercise by comparing total units sold by category. Then filter the complete orders to a date range and export a second summary.
Check whether its totals reconcile with the selected records.
These variations help you practise the sequence: inspect, clean, calculate, check, and communicate.
For additional practice briefs, continue with Python Data Analysis Projects to Build Practical Skills.
For a structured next step, review the Python Programming Bootcamp (Data Analysis & Automation) syllabus and prerequisites against the skills you want to develop.