Pandas Tutorial: Data Analysis with Python for Beginners
December 5, 2026 · 11 min read

This pandas tutorial takes you from an empty Python file to a complete first analysis: loading data, cleaning it, filtering, grouping, reshaping and reading from a SQL database. pandas is the most widely used Python library for working with tables of data, the kind you might otherwise wrestle with in Excel, and it underpins a huge share of data analysis, reporting and machine learning work. If you can write a few lines of Python, you can be productive with pandas within an afternoon.
It is also a good moment to learn, because pandas changed significantly this year. pandas 3.0, released on 21 January 2026, made a dedicated string data type the default, adopted Copy-on-Write as the only behaviour for copies and views, and added a new pd.col() syntax for building column expressions. Older tutorials do not cover these changes, so this guide uses pandas 3 throughout, and every code example was run with pandas 3.0 to produce the output shown. Python itself remains one of the most used languages, at 58% of respondents in the Stack Overflow Developer Survey 2026.
What Is pandas and Why Use It?
pandas gives Python two core structures. A DataFrame is a table with labelled columns and rows, like a spreadsheet or a SQL table, and a Series is a single labelled column. Built on top of NumPy, pandas can load data from CSV files, Excel workbooks, JSON, SQL databases and Parquet files, then clean, combine, summarise and export it with short, readable code.
Compared with spreadsheets, pandas handles far larger datasets, records every step in code so analyses are repeatable and reviewable, and automates work that would otherwise be done by hand each week. Compared with SQL, it is more flexible for messy data, statistics and feeding machine learning libraries. The two work well together, as you will see below. If you are still choosing a first language, our comparison of Python vs JavaScript explains why Python dominates data work.
Install pandas 3
pandas 3 requires Python 3.11 or newer and NumPy 1.26 or newer, according to the release notes. Install it with pip, ideally inside a virtual environment:
python -m venv .venv
source .venv/bin/activate # on Windows: .venv\Scripts\activate
pip install pandas pyarrow
python -c "import pandas as pd; print(pd.__version__)"
PyArrow is optional, but when it is installed pandas uses it to make the new string type faster and more memory-efficient. Many people also install Jupyter, which lets you run code in small steps and see tables and charts immediately, the most comfortable way to explore data while learning.
Pandas Tutorial: Your First Analysis, Step by Step
The script below analyses a small set of online orders. It is deliberately realistic: the data includes a duplicated row and a missing price, just like real exports. Save it as a file and run it, or paste it into a notebook cell by cell:
# pandas_tutorial.py: a complete first analysis with pandas 3
import io
import sqlite3
import pandas as pd
CSV = """order_id,order_date,customer,city,product,category,quantity,unit_price
1001,2026-10-03,Ayesha,Lahore,Wireless Mouse,Accessories,2,19.50
1002,2026-10-03,Ben,London,Laptop Stand,Accessories,1,49.00
1003,2026-10-11,Carla,Lahore,27in Monitor,Displays,1,189.00
1004,2026-10-19,Ayesha,Lahore,USB-C Hub,Accessories,1,
1005,2026-11-02,Dev,Karachi,27in Monitor,Displays,2,189.00
1006,2026-11-02,Ben,London,Wireless Mouse,Accessories,3,19.50
1007,2026-11-15,Carla,Lahore,Mechanical Keyboard,Accessories,1,89.00
1007,2026-11-15,Carla,Lahore,Mechanical Keyboard,Accessories,1,89.00
"""
# 1. Load: in real projects this is pd.read_csv("orders.csv", parse_dates=["order_date"])
df = pd.read_csv(io.StringIO(CSV), parse_dates=["order_date"])
print("Shape:", df.shape)
print("Text columns use the new str dtype:", df["customer"].dtype)
# 2. Clean: remove exact duplicates and rows with no price
print("Duplicate rows:", df.duplicated().sum(), "| missing prices:", df["unit_price"].isna().sum())
df = df.drop_duplicates().dropna(subset=["unit_price"])
# 3. Add columns with pd.col() expressions, new in pandas 3
df = df.assign(
revenue=pd.col("quantity") * pd.col("unit_price"),
month=pd.col("order_date").dt.strftime("%Y-%m"),
)
# 4. Filter rows
print("Orders worth 100 or more:", df.loc[df["revenue"] >= 100, "order_id"].tolist())
# 5. Group and summarise
summary = (
df.groupby("category")
.agg(orders=("order_id", "nunique"), units=("quantity", "sum"), revenue=("revenue", "sum"))
.sort_values("revenue", ascending=False)
)
print(summary)
# 6. Reshape: revenue by city and month
print(df.pivot_table(index="city", columns="month", values="revenue", aggfunc="sum", fill_value=0))
# 7. Work with SQL databases: write the clean data, then query it back
con = sqlite3.connect(":memory:") # with MySQL, pass a SQLAlchemy engine instead
df.to_sql("orders", con, index=False)
print(pd.read_sql("SELECT customer, SUM(revenue) AS revenue FROM orders GROUP BY customer ORDER BY revenue DESC LIMIT 3", con))
Running it with pandas 3 prints:
Shape: (8, 8)
Text columns use the new str dtype: str
Duplicate rows: 1 | missing prices: 1
Orders worth 100 or more: [1003, 1005]
orders units revenue
category
Displays 2 3 567.0
Accessories 4 7 235.5
month 2026-10 2026-11
city
Karachi 0.0 378.0
Lahore 228.0 89.0
London 49.0 58.5
customer revenue
0 Dev 378.0
1 Carla 278.0
2 Ben 107.5
Step 1: Load the data
pd.read_csv() reads a CSV file into a DataFrame, and parse_dates converts the date column into real dates rather than text. Sister functions include read_excel, read_json, read_parquet and read_sql. The shape (8, 8) tells you there are eight rows and eight columns, and the next line confirms that text columns now use pandas 3's dedicated str type instead of the old generic object type.
Step 2: Inspect and clean
Always check data before trusting it. duplicated() finds repeated rows and isna() finds missing values; here there is one duplicate order and one order without a price. drop_duplicates() and dropna() remove them. In real work, find out why a value is missing before deleting it: fillna() can replace gaps with a default or calculated value when that is more appropriate. Other everyday inspection tools are head(), info() and describe().
Step 3: Add calculated columns
assign() adds new columns, and pandas 3's pd.col() lets you refer to existing columns by name, so pd.col("quantity") * pd.col("unit_price") calculates revenue for every row at once. Operations like this are vectorised: pandas applies them to whole columns in optimised code, which is far faster than looping over rows in Python.
Step 4: Filter rows
A condition such as df["revenue"] >= 100 produces a column of true and false values, and df.loc[condition, "order_id"] selects the matching rows and the column you want. Combine conditions with & for "and" and | for "or", wrapping each condition in brackets.
Step 5: Group and summarise
groupby() splits the data by category, and agg() with named aggregations calculates several summaries at once: the number of distinct orders, total units and total revenue. This is the pandas equivalent of SQL's GROUP BY and of a spreadsheet pivot, and it is the step you will use most.
Step 6: Reshape with a pivot table
pivot_table() turns rows into a grid, here cities down the side and months across the top, with fill_value=0 replacing empty cells. Related tools include melt() for the reverse operation and merge() for joining two DataFrames on a shared column, just like a SQL join.
Step 7: Work with SQL databases
to_sql() writes a DataFrame to a database table and read_sql() runs a query and returns the result as a DataFrame. The example uses SQLite so it runs anywhere, but the same code works with MySQL or PostgreSQL by passing a SQLAlchemy engine created from a connection string, which makes pandas a convenient bridge between application databases and analysis.
What Changed in pandas 3
- Strings have their own type. Text columns are inferred as
strrather thanobject, which is faster and safer. Code that checks forobjectcolumns may need updating; the string migration guide explains the details. - Copy-on-Write is the only mode. Every selection behaves like a copy, so changing it never silently changes the original DataFrame, and the old
SettingWithCopyWarningis gone. Chained assignment no longer works:
# pandas 3: chained assignment no longer changes the original DataFrame
df[df["city"] == "Lahore"]["unit_price"] = 0 # no effect on df; pandas warns with ChainedAssignmentError
df.loc[df["city"] == "Lahore", "unit_price"] = 0 # do this instead
- Column expressions with
pd.col()replace manylambdafunctions inassign()and similar methods. - Datetime resolution changed. Dates parsed from strings now default to microsecond rather than nanosecond resolution, which matters if you convert timestamps to integers.
- Deprecated features were removed. The pandas team recommends upgrading to pandas 2.3 first, fixing any warnings, then moving to 3.0.
Ten Methods You Will Use Every Day
head()andtail()to preview the first or last rows.info()to see column types, row counts and missing values.describe()for quick statistics on numeric columns.value_counts()to count how often each value appears in a column.sort_values()to order rows by one or more columns.rename()to tidy messy column names from exports.astype()to convert columns to the right type, such as text to numbers.merge()to join two tables on a shared key.to_csv()andto_excel()to save results for colleagues.- The
straccessor, with methods such asstr.lower()andstr.contains(), for cleaning text.
Common Beginner Mistakes
- Looping over rows with
forloops oriterrows()instead of using vectorised column operations. - Ignoring data types, such as numbers stored as text, which break calculations and sorting. Check
dtypesearly. - Loading more than you need. For large files, read only the columns you use with
usecols, or process them in chunks. - Forgetting that missing values spread: sums and averages skip them by default, but comparisons and string operations may not behave as you expect.
- Relying on chained assignment from older tutorials, which no longer modifies data in pandas 3.
Visualise and Share Your Results
For quick charts, df.plot() draws line, bar and other charts through Matplotlib, and libraries such as Seaborn and Plotly produce more polished visuals. When colleagues need interactive dashboards rather than scripts, export cleaned data to a database or file that a BI tool reads; our comparison of Power BI vs Tableau vs Looker Studio covers the main options.
When to Move Beyond pandas
pandas loads data into memory, so it is ideal for files up to a few gigabytes on a normal laptop. For larger datasets, DuckDB runs fast SQL directly on files, as in the example in our guide to data warehouse vs data lake, and Polars offers a DataFrame library designed for speed and larger-than-memory work. When an analysis becomes a regular, scheduled job, move it into a proper pipeline, as described in our guide to ETL vs ELT. Understanding how databases store data, covered in SQL vs NoSQL, also makes you a better analyst.
Practice Projects to Build Your Skills
The best way to lock in what this pandas tutorial covered is to analyse data you care about:
- Analyse your own bank or shopping exports: monthly spending by category, with a chart.
- Download a public dataset from Kaggle and answer five questions about it.
- Combine two datasets, such as sales and weather, with
merge()and look for patterns. - Build a small weekly report script that reads a CSV, summarises it and saves the results.
Our lists of beginner coding projects and final-year project ideas include more data projects, and data analysis features prominently among the highest-paying IT skills.
Frequently Asked Questions
Is pandas hard to learn?
No. If you know basic Python, you can load, clean and summarise data within a few hours. Mastering performance, reshaping and time-series features takes longer, but the everyday essentials are quick to learn.
Do I need to know Python before learning pandas?
You need the basics: variables, lists, dictionaries, functions and importing libraries. Many people learn pandas alongside Python because it gives practical, motivating results quickly.
What is the difference between pandas and NumPy?
NumPy provides fast arrays of numbers for mathematical work. pandas builds on NumPy to add labelled tables with mixed data types, missing-value handling, grouping and easy reading and writing of files and databases.
Is pandas still worth learning in 2026?
Yes. pandas remains the standard tool for data analysis in Python, is used across data science and machine learning, and its 3.0 release has modernised it. Newer tools such as Polars and DuckDB complement it rather than replace it.
What is new in pandas 3?
pandas 3.0, released in January 2026, made a dedicated string type the default, made Copy-on-Write the only behaviour, added pd.col() expressions, changed default datetime resolution and removed many deprecated features.
Can pandas read data from MySQL?
Yes. Use pd.read_sql() with a SQLAlchemy engine connected to MySQL, PostgreSQL or most other databases, and to_sql() to write DataFrames back to a table.
Put Your Data to Work
Finished this pandas tutorial and want help with real business data? We build data pipelines, Python analytics tools and dashboards that turn raw business data into decisions. Contact our team to get more from your data.