Online Python tutoring
Home

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().

Learn Pandas with Practical Support

Need help understanding DataFrames, data cleaning or Python data analysis? Build confidence with structured examples and one-to-one tutoring.

Get 1-on-1 Python Tutoring

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.

Python
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.

How to use these exercises: attempt the task first, write and run your own code, then compare your approach with the solution. Some tasks can be solved in more than one correct way.

2. Beginner Pandas exercises

Exercise 1: Display the first five rows

Show the first five rows of the sales DataFrame.

Solution
Python
sales.head()

Exercise 2: Find the number of rows and columns

Return the shape of the DataFrame.

Solution
Python
sales.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.

Solution
Python
sales[["Employee", "Sales"]]

Exercise 4: Filter sales greater than 1,000

Return only records where Sales is greater than 1,000.

Solution
Python
sales[sales["Sales"] > 1000]

Exercise 5: Sort sales from highest to lowest

Sort the DataFrame by Sales in descending order.

Solution
Python
sales.sort_values("Sales", ascending=False)

Exercise 6: Add a commission column

Create a Commission column equal to 5% of Sales.

Solution
Python
sales["Commission"] = sales["Sales"] * 0.05

Exercise 7: Rename a column

Rename Units to Units_Sold.

Solution
Python
sales = sales.rename(columns={"Units": "Units_Sold"})

Exercise 8: Count employees

Count how many records are present for each employee.

Solution
Python
sales["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.

Solution
Python
sales[(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.

Solution
Python
sales["Sales"].mean()

Exercise 11: Group sales by department

Calculate total Sales for each Department.

Solution
Python
sales.groupby("Department")["Sales"].sum()

Exercise 12: Calculate several group statistics

For each department, calculate total sales, average sales and record count.

Solution
Python
sales.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.

Solution
Python
sales.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.

Solution
Python
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.

Solution
Python
sales.nlargest(3, "Sales")

4. Pandas data-cleaning exercises

Exercise 16: Count missing values in each column

Find the number of missing values per column.

Solution
Python
sales.isna().sum()

Exercise 17: Fill missing Sales with the median

Replace missing Sales values with the median Sales.

Solution
Python
sales["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.

Solution
Python
sales_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.

Solution
Python
sales["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.

Solution
Python
sales["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.

Solution
Python
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.

Solution
Python
employee_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.

Solution
Python
sales.groupby("Department")["Employee"].nunique()

Exercise 24: Create a pivot table

Summarise total Sales by Department and Region.

Solution
Python
pd.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.

Solution
Python
department_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:

  1. Remove exact duplicate records.
  2. Standardise employee and department text.
  3. Check and handle missing Sales values using a method appropriate to your goal.
  4. Group by Department to calculate total and average Sales.
  5. Sort departments from highest to lowest total sales.
  6. 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.

Python
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

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.

Need help with Python or Pandas?

Get personalised help with Python programming, Pandas, data analysis and practical projects.

Explore Python Tutoring



Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net