Welcome! This tutorial will teach you the essential Pandas skills you need to start working with data in Python.
We'll use one small car sales dataset throughout the tutorial. This makes it easier to follow because you'll keep working with the same data as you learn new things.
You don't need to know Pandas already. You only need basic Python knowledge.
By the end, you'll be able to:
Understand DataFrames and Series
Load and save data
Inspect and understand your data
Select, filter, and sort rows and columns
Clean messy data and handle missing values
Create new features
Summarize data with groupby and crosstab
Create basic visualizations
Apply custom transformations
We'll create the car sales dataset ourselves. It will also contain some common problems that you may find in real-world data, such as messy prices, inconsistent text, and missing values.
0. What is Pandas?
Pandas is a Python library that helps us work with table-like data.
Think about a table in Excel:
Name
Age
City
Alice
25
New York
Bob
30
London
Pandas lets us create, read, change, filter, and analyze tables like this using Python.
Pandas mainly gives us two important things:
DataFrame – the entire table
Series – one column from the table
A simple way to remember this:
DataFrame = whole table
Series = one column
1. Setup
First, install Pandas if you haven't already.
Run this in your terminal:
pip install pandas
Then import Pandas in your Python script or notebook:
import pandas as pd
Here, pd is just a shorter name for Pandas. Without as pd, we would have to write pandas every time. With as pd, we can simply write:
pd.DataFrame()
instead of:
pandas.DataFrame()
2. A Quick First DataFrame
Before working with our car data, let's create a very small DataFrame.
Name Age City
0 Alice 25 New York
1 Bob 30 London
2 Charlie 35 Paris
3 Diana 28 Tokyo
Let's understand what we're seeing.
There are three columns:
Name
Age
City
There are also numbers on the left:
0
1
2
3
These numbers are called the index. Pandas automatically creates an index for each row. The index helps Pandas identify each row. It is not one of our actual data columns.
3. Loading the Car Sales Dataset
Now let's create the dataset we'll use for the rest of the tutorial.
Our dataset contains these columns:
Make – the car manufacturer
Model – the car model
Year – the manufacturing year
Price – the price of the car
Odometer (KM) – how many kilometers the car has been driven
Doors – number of doors
Color – the car's color
Some of the data is intentionally messy. For example, the price contains $ and commas, and Toyota is written in different ways.
Make Model Year Price Odometer (KM) Doors Color
0 Toyota Corolla 2015 $15,000 120000 4 White
1 Honda Civic 2018 $18,500 60000 4 Black
2 toyota Camry 2017 $16,200 85000 4 Red
3 Ford Focus 2016 $10,000 130000 5 Blue
4 BMW 3 Series 2019 $35,000 45000 4 Silver
5 Honda Accord 2020 $22,000 20000 4 White
6 TOYOTA RAV4 2014 $14,500 150000 4 Red
7 Ford Fiesta 2018 $12,000 90000 3 Green
8 BMW 5 Series 2017 $32,500 55000 4 Black
9 Nissan Altima 2016 $17,000 100000 4 Blue
We'll keep using this DataFrame. Later, we'll save it as a CSV file and load it again.
4. Data Structures: Series and DataFrame
Pandas has two main data structures:
Series – one column
DataFrame – the complete table
Our car_sales variable is a DataFrame. Each column inside car_sales is a Series.
For example:
# Get the 'Make' column as a Seriesmake_series = car_sales["Make"]print(type(make_series))print(make_series)
Output:
<class 'pandas.core.series.Series'>
0 Toyota
1 Honda
2 toyota
3 Ford
4 BMW
5 Honda
6 TOYOTA
7 Ford
8 BMW
9 Nissan
Name: Make, dtype: object
So when we do:
car_sales["Make"]
we get one Series containing the Make column.
A Series has:
an index
values
The index is on the left, and the actual values are on the right.
5. Import & Export
In real projects, data usually doesn't come directly from a Python dictionary. It might come from a CSV file. Pandas makes it easy to save data to a file and read it back.
Save to CSV
We can save our DataFrame as a CSV file:
car_sales.to_csv("car_sales.csv", index=False)
The index=False means:
Don't save Pandas's index as an extra column in the CSV file.
Only rows where Make is exactly "Toyota" will be returned. Notice that "toyota" and "TOYOTA" are not returned. That's because Python treats these as different strings. We'll fix this later when we clean our data.
Multiple conditions
We can combine conditions.
For example:
Find cars with more than 100,000 KM and exactly 4 doors.
Doors 3 4 5
Make
BMW 0 2 0
Ford 1 1 1
Honda 0 2 0
Nissan 0 1 0
TOYOTA 0 1 0
Toyota 0 1 0
toyota 0 1 0
We can read this as:
How many cars of each make have 3, 4, or 5 doors?
For example:
BMW 0 2 0
means BMW has:
0 cars with 3 doors
2 cars with 4 doors
0 cars with 5 doors
Notice that Toyota appears three times:
TOYOTA
Toyota
toyota
Pandas treats them as different values because their capitalization is different. We'll clean this later.
13. GroupBy – Aggregating by Group
groupby() is useful when we want to divide our data into groups and calculate something for each group.
For example, we can group cars by their manufacturer:
car_sales.groupby("Make").mean(numeric_only=True)
This asks:
For each car manufacturer, what are the average numeric values?
Output:
Year Odometer (KM) Doors
Make
BMW 2018.0 50000.0 4.000000
Ford 2017.0 110000.0 4.000000
Honda 2019.0 40000.0 4.000000
Nissan 2016.0 100000.0 4.000000
TOYOTA 2014.0 150000.0 4.000000
Toyota 2015.0 120000.0 4.000000
toyota 2017.0 85000.0 4.000000
The important idea is:
groupby("Make")
puts rows with the same Make together.
Then:
.mean()
calculates the average for each group.
Again, because Toyota has different capitalization, Pandas creates three separate groups. We'll fix this in the cleaning section.
14. Basic Data Visualization
Pandas can also create simple charts. Pandas uses Matplotlib for its built-in plotting features.
Line plot
We can create a basic line plot of the odometer values:
car_sales["Odometer (KM)"].plot()
This gives us a visual representation of the values.
Histogram
We can also create a histogram:
car_sales["Odometer (KM)"].hist()
A histogram helps us see how the odometer values are distributed. For example, it can help us see whether most cars have lower or higher mileage.
In a plain Python script (as opposed to a Jupyter notebook), Pandas charts won't appear unless you import Matplotlib and call show():
import matplotlib.pyplot as pltcar_sales["Odometer (KM)"].plot()plt.show()
In notebooks, the chart usually displays automatically after the cell runs.
15. Cleaning Data
Now let's start fixing the messy parts of our dataset. Real-world data is often not perfectly clean. Our dataset has a few problems:
Prices contain $ and ,
The same manufacturer is written with different capitalization
We'll introduce some missing values
Let's fix these one at a time.
15.1 Clean the Price Column
Our prices currently look like this:
$15,000
$18,500
$16,200
These are strings, not numbers. We want them to become:
15000
18500
16200
First, remove the $:
.str.replace("$", "", regex=False)
Then remove the commas:
.str.replace(",", "", regex=False)
Finally, convert the result to a float:
.astype(float)
We can do all of that together:
car_sales["Price"] = ( car_sales["Price"] .astype(str) # Convert to string type first to ensure .str accessor works .str.replace("$", "", regex=False) # remove dollar sign .str.replace(",", "", regex=False) # remove commas .astype(float) # convert to float)print(car_sales["Price"].head())
Let's see the payoff. Compare this groupby with the one in Section 13 — the three Toyota spellings have collapsed into one group:
car_sales.groupby("Make").mean(numeric_only=True)
Output:
Year Odometer (KM) Doors
Make
bmw 2018.0 50000.0 4.0
ford 2017.0 110000.0 4.0
honda 2019.0 40000.0 4.0
nissan 2016.0 100000.0 4.0
toyota 2015.5 118333.3 4.0
The toyota row now averages the three Toyotas together, which is what we actually want.
16. Handling Missing Data
Real-world datasets often contain missing values. For example, a car might not have its mileage recorded. Let's create some missing values ourselves so we can learn how to handle them. We'll use None. Pandas will treat these as missing values, usually shown as NaN.
Make 0
Model 0
Year 0
Price 1
Odometer (KM) 1
Doors 1
Color 0
dtype: int64
This tells us:
Price has 1 missing value
Odometer (KM) has 1 missing value
Doors has 1 missing value
The other columns have no missing values
Fill vs. drop
Before filling anything, it helps to see what dropna() would do on the real data. It would remove every row that contains any missing value:
# Preview only — this would remove the 3 rows with missing values# car_sales.dropna()
In our case, that would throw away 3 of our 10 rows, which is a lot. So instead of dropping, we'll fill the missing values with reasonable replacements.
Fill Missing Values
One way to handle missing data is to replace the missing value with something else. We can use a calculated value such as the mean or median.
We can also choose a specific value. For example, we can replace the missing price with 0:
car_sales["Price"] = car_sales["Price"].fillna(0)
Now check the missing values again:
car_sales.isna().sum()
All values should now be zero.
Drop Missing Values
Another option is to remove rows that contain missing values.
We can use:
car_sales.dropna(inplace=True)
This removes rows containing any NaN. In our example, we've already filled the missing values, so we don't need to use dropna(). In real projects, whether you should fill or remove missing data depends on the situation.
17. Creating New Columns (Feature Engineering)
We can create new columns using existing data. This is sometimes called feature engineering. Let's look at several ways to create a new column.
From a Series
We can create a Series containing the number of seats:
We can also create a normal named function and pass that function to .apply().
23. Putting It All Together: A Full Workflow
Now let's combine many of the things we've learned into one workflow. This workflow reuses the DataFrame from Section 3. If you're running this as a fresh script, run Section 3 first to define car_sales.
import pandas as pd# Reuse the DataFrame from Section 3 (defined as `car_sales`).# Work on a copy so the rest of the tutorial's data isn't changed.df = car_sales.copy()# 1. Clean Pricedf["Price"] = ( df["Price"] .astype(str) .str.replace("$", "", regex=False) .str.replace(",", "", regex=False) .astype(float))# 2. Clean Makedf["Make"] = df["Make"].str.lower()# 3. Introduce and handle missing valuesdf.loc[2, "Odometer (KM)"] = Nonedf["Odometer (KM)"] = df["Odometer (KM)"].fillna(df["Odometer (KM)"].mean())# 4. Create a new featuredf["Price per 1000 km"] = df["Price"] / (df["Odometer (KM)"] / 1000)# 5. Filterfiltered = df[df["Price"] < 20000]# 6. Group summarysummary = filtered.groupby("Make")["Price"].mean()print(summary)# 7. Savedf.to_csv("cleaned_car_sales.csv", index=False)
Let's follow what this code does:
Step 1 — Start from a copy
df = car_sales.copy()
We work on a copy of the DataFrame from Section 3 so the workflow is runnable end-to-end without redefining the data.
Step 2 — Clean the price
df["Price"] = ...
We remove $ and commas and convert the values to numbers.
Step 3 — Clean the make
df["Make"] = df["Make"].str.lower()
This makes the manufacturer names consistent.
Step 4 — Handle missing data
We create a missing odometer value and then replace it with the average.