Pandas Exercises: 25 Practice Questions with Solutions
Practising with real tables is one of the best ways to learn Pandas. This collection of Pandas exercises helps you practise the most useful data-analysis operations in Python, from creating a DataFrame and selecting rows to grouping, cleaning and joining datasets.
Each question has a clear task and a worked solution. Try solving the question before opening or reading its answer. The exercises progress from beginner to intermediate level and use small datasets so you can focus on the Pandas operation rather than complicated data preparation.
New to the library? Start with the complete Pandas tutorial, or review Pandas DataFrames, selecting rows and columns, filtering a DataFrame and groupby().
1. Set up the practice dataset
Run the following code in Jupyter Notebook, Google Colab or another Python environment with Pandas installed. The same dataset is reused in several questions.
import pandas as pd
import numpy as np
sales = pd.DataFrame({
"Employee": ["Aisha", "Bilal", "Chen", "Dina", "Aisha", "Bilal", "Evan", "Farah"],
"Department": ["Sales", "IT", "IT", "Sales", "Sales", "IT", "Finance", "Finance"],
"Region": ["North", "South", "North", "East", "North", "South", "East", "West"],
"Sales": [1200, 900, 1500, 700, 1200, 1100, 1800, np.nan],
"Units": [12, 9, 15, 7, 12, 11, 18, 10],
"Rating": [4.5, 3.8, 4.9, 4.0, 4.5, 4.1, 4.7, np.nan]
})
print(sales)
The dataset intentionally contains a repeated record and some missing values. These are useful for practising common data-analysis tasks.
2. Beginner Pandas exercises
Exercise 1: Display the first five rows
Show the first five rows of the sales DataFrame.
sales.head()
Exercise 2: Find the number of rows and columns
Return the shape of the DataFrame.
Solutionsales.shape
shape returns a tuple containing the row count followed by the column count.
Exercise 3: Select two columns
Create a DataFrame containing only Employee and Sales.
sales[["Employee", "Sales"]]
Exercise 4: Filter sales greater than 1,000
Return only records where Sales is greater than 1,000.
Solutionsales[sales["Sales"] > 1000]
Exercise 5: Sort sales from highest to lowest
Sort the DataFrame by Sales in descending order.
Solutionsales.sort_values("Sales", ascending=False)
Exercise 6: Add a commission column
Create a Commission column equal to 5% of Sales.
sales["Commission"] = sales["Sales"] * 0.05
Exercise 7: Rename a column
Rename Units to Units_Sold.
sales = sales.rename(columns={"Units": "Units_Sold"})
Exercise 8: Count employees
Count how many records are present for each employee.
Solutionsales["Employee"].value_counts()
3. Intermediate Pandas exercises
Exercise 9: Filter using two conditions
Find records in the IT department with Sales of at least 1,000.
Solutionsales[(sales["Department"] == "IT") & (sales["Sales"] >= 1000)]
Put each comparison in parentheses and use & for element-wise AND.
Exercise 10: Calculate average sales
Calculate the mean of the Sales column, excluding missing values.
Solutionsales["Sales"].mean()
Exercise 11: Group sales by department
Calculate total Sales for each Department.
Solutionsales.groupby("Department")["Sales"].sum()
Exercise 12: Calculate several group statistics
For each department, calculate total sales, average sales and record count.
Solutionsales.groupby("Department").agg(
total_sales=("Sales", "sum"),
average_sales=("Sales", "mean"),
records=("Employee", "size")
)
Exercise 13: Find the highest sales record
Return the row with the maximum Sales value.
Solutionsales.loc[sales["Sales"].idxmax()]
This assumes at least one non-missing Sales value exists.
Exercise 14: Create a conditional category
Create a column named Performance with “High” for sales of 1,200 or more and “Standard” otherwise.
sales["Performance"] = np.where(
sales["Sales"] >= 1200, "High", "Standard"
)
Missing Sales values will fall into the “Standard” branch in this example. In a real analysis, you may want to handle missing values separately.
Exercise 15: Select the top three sales records
Return the three largest non-missing sales values with their rows.
Solutionsales.nlargest(3, "Sales")
4. Pandas data-cleaning exercises
Exercise 16: Count missing values in each column
Find the number of missing values per column.
Solutionsales.isna().sum()
Exercise 17: Fill missing Sales with the median
Replace missing Sales values with the median Sales.
Solutionsales["Sales"] = sales["Sales"].fillna(sales["Sales"].median())
For machine-learning work, calculate imputation values using training data only, then apply them to validation or test data.
Exercise 18: Remove duplicate rows
Create a new DataFrame with exact duplicate rows removed.
Solutionsales_unique = sales.drop_duplicates()
If duplicates should be defined by only selected fields, pass those fields to subset.
Exercise 19: Standardise employee names
Remove extra spaces and convert Employee names to title case.
Solutionsales["Employee"] = sales["Employee"].str.strip().str.title()
Exercise 20: Convert Sales to a numeric type
Convert Sales to numeric values, turning invalid entries into missing values.
Solutionsales["Sales"] = pd.to_numeric(sales["Sales"], errors="coerce")
5. Group, merge and combine DataFrames
Exercise 21: Concatenate two DataFrames
Append new_sales to sales and create a fresh integer index.
new_sales = pd.DataFrame({
"Employee": ["George"],
"Department": ["IT"],
"Region": ["North"],
"Sales": [950],
"Units": [8],
"Rating": [4.2]
})
combined = pd.concat([sales, new_sales], ignore_index=True)
Use matching column names and compatible data types when combining records.
Exercise 22: Merge employee details
Join sales records to a separate employee lookup table using Employee.
Solutionemployee_details = pd.DataFrame({
"Employee": ["Aisha", "Bilal", "Chen", "Dina"],
"Years_Experience": [4, 6, 3, 8]
})
merged = sales.merge(employee_details, on="Employee", how="left")
A left merge keeps every row from sales. If the lookup table has repeated employee keys, the merge can multiply rows.
Exercise 23: Find unique employees per department
Count the distinct employee names in each department.
Solutionsales.groupby("Department")["Employee"].nunique()
Exercise 24: Create a pivot table
Summarise total Sales by Department and Region.
Solutionpd.pivot_table(
sales,
values="Sales",
index="Department",
columns="Region",
aggfunc="sum",
fill_value=0
)
Exercise 25: Find each department's share of total sales
Calculate department sales totals and each department's proportion of overall sales.
Solutiondepartment_sales = sales.groupby("Department")["Sales"].sum()
share = department_sales / department_sales.sum()
result = pd.DataFrame({
"total_sales": department_sales,
"share_of_sales": share
})
The proportion is between 0 and 1. Multiply it by 100 if you want a percentage.
6. Mini project: clean and summarise sales data
Use the skills above to complete a small end-to-end analysis:
- Remove exact duplicate records.
- Standardise employee and department text.
- Check and handle missing Sales values using a method appropriate to your goal.
- Group by Department to calculate total and average Sales.
- Sort departments from highest to lowest total sales.
- Write a short conclusion describing the results and any data-quality limitations.
One possible starting point is shown below. Decide whether median imputation is appropriate before using it; filling missing sales with a number changes the interpretation of the total.
clean = sales.drop_duplicates().copy()
clean["Employee"] = clean["Employee"].str.strip().str.title()
summary = (
clean.groupby("Department", dropna=False)["Sales"]
.agg(total_sales="sum", average_sales="mean", records="size")
.sort_values("total_sales", ascending=False)
)
print(summary)
7. How to practise Pandas effectively
- Type the code yourself. Writing and changing examples helps you understand how each operation works.
- Predict the output first. This is especially helpful for filtering, grouping and joining.
- Inspect intermediate results. Use
head(),shape,dtypesandisna().sum(). - Test edge cases. Try missing values, duplicate keys, empty results and unexpected categories.
- Read the error message. Check spelling, column names, data types and parentheses before changing the whole solution.
- Practise on new data. Repeat the same operations on a CSV or Excel file of your own.
Continue learning with Pandas DataFrames, filtering rows, groupby(), merge() and concat().
8. Frequently asked questions
Are these Pandas exercises suitable for beginners?
Yes. The first exercises cover basic DataFrame inspection, selecting columns, filtering and sorting. Later questions introduce cleaning, grouping and combining data.
Where can I run these Pandas practice questions?
You can run them in Jupyter Notebook, Google Colab, or another Python environment with Pandas and NumPy installed.
Should I memorise Pandas methods?
Focus on understanding what each method does, what it returns and how it changes the data. Regular practice is more useful than memorising isolated syntax.
What should I learn after these exercises?
Practise importing real CSV and Excel files, handling data-quality problems, joining datasets and producing summaries. Then apply these skills to a small analytics project.
Do all questions have only one correct answer?
No. Several Pandas tasks can be solved in different ways. Compare the readability, accuracy and performance of your approach with the provided solution.
