Welcome to this practical Python Pandas assignment by Pivot Edu Unit. In these exercises, you will learn how to work with real-world datasets using Pandas. Each question includes a problem statement, step-by-step instructions, Python code, and an explanation of the expected output. These exercises are suitable for students learning Python programming, data analysis, and data science.
Getting Started: Install and Import Pandas
Before starting the exercises, install Pandas if it is not already installed in your Python environment.
pip install pandas
Import the Pandas library in your Python program.
import pandas as pd
Q1: Create a Student DataFrame
Problem: A coaching institute wants to maintain student records containing names, courses, and marks. Create a Pandas DataFrame and display all student records.
Step 1: Import Pandas.
Step 2: Create a dictionary containing student names, courses, and marks.
Step 3: Convert the dictionary into a DataFrame.
Step 4: Display the complete DataFrame.
import pandas as pd
data = {
'Name': ['Aman', 'Priya', 'Rahul', 'Neha', 'Karan'],
'Course': ['Python', 'Data Analytics', 'Python', 'Web Design', 'Python'],
'Marks': [78, 92, 65, 85, 88]
}
df = pd.DataFrame(data)
print(df)
Expected output:
Name Course Marks
0 Aman Python 78
1 Priya Data Analytics 92
2 Rahul Python 65
3 Neha Web Design 85
4 Karan Python 88
Explanation: A DataFrame is a two-dimensional table with rows and columns. The dictionary keys become column names, while the corresponding lists provide the column values.
Q2: Filter Students Who Scored More Than 80 Marks
Problem: The institute wants to identify students who scored more than 80 marks so they can be considered for a merit list.
Step 1: Create the student DataFrame from Question 1.
Step 2: Apply a condition to the Marks column.
Step 3: Display only the rows that satisfy the condition.
high_scorers = df[df['Marks'] > 80]
print(high_scorers)
Expected output:
Name Course Marks
1 Priya Data Analytics 92
3 Neha Web Design 85
4 Karan Python 88
Explanation: The expression df['Marks'] > 80 creates a Boolean condition. Pandas returns only the rows where the condition is True. The original DataFrame remains unchanged.
Practice extension: Display students who scored at least 70 marks and students who scored between 70 and 90 marks, including both boundaries.
Q3: Read Student Records from a CSV File
Problem: A coaching institute stores student records in a file named students.csv. Read the file using Pandas and display its first five records, column names, and total number of rows.
Step 1: Create a CSV file named students.csv with the following data.
Name,Course,Marks,Fees
Aman,Python,78,6000
Priya,Data Analytics,92,12000
Rahul,Python,65,6000
Neha,Web Design,85,8000
Karan,Python,88,6000
Simran,Data Analytics,74,12000
Step 2: Place the file in the same folder as your Python script.
Step 3: Use read_csv() to load the data.
Step 4: Display the first five rows, column names, and row count.
import pandas as pd
df = pd.read_csv('students.csv')
print('First five records:')
print(df.head())
print('Column names:')
print(df.columns.tolist())
print('Total students:', len(df))
Expected output for the row count:
Total students: 6
Explanation: read_csv() loads tabular data from a CSV file into a DataFrame. The head() method displays the first five rows by default, columns.tolist() returns the column names as a list, and len(df) gives the number of rows.
Practice extension: Display the last three records using tail(3) and inspect the dataset using df.info().
Q4: Handle Missing Values in Student Data
Problem: Some student records contain missing marks or course names. Identify the missing values and replace missing marks with the average marks. Replace missing course names with Unknown.
Step 1: Create a DataFrame containing missing values.
Step 2: Use isnull().sum() to count missing values in each column.
Step 3: Calculate the average of the available marks.
Step 4: Fill missing marks and course names.
import pandas as pd
data = {
'Name': ['Aman', 'Priya', 'Rahul', 'Neha'],
'Course': ['Python', None, 'Python', 'Web Design'],
'Marks': [78, 92, None, 85]
}
df = pd.DataFrame(data)
print('Missing values before cleaning:')
print(df.isnull().sum())
average_marks = df['Marks'].mean()
df['Marks'] = df['Marks'].fillna(average_marks)
df['Course'] = df['Course'].fillna('Unknown')
print('Cleaned data:')
print(df)
Expected result: The missing course name becomes Unknown, and the missing mark becomes 85.0 because the average of 78, 92, and 85 is 85.
Explanation: isnull().sum() counts missing values in each column. mean() ignores missing numeric values by default, while fillna() replaces missing entries with the specified value. Cleaning missing values helps prepare datasets for reliable analysis.
Important: Remove the accidental leading space before data in the code if your editor flags an indentation error. The dictionary assignment should begin at the start of the line.
Q5: Calculate Course-Wise Average Marks
Problem: The institute director wants to compare the academic performance of students enrolled in different courses. Calculate the average marks for each course.
Step 1: Load students.csv from Question 3.
Step 2: Group the records using the Course column.
Step 3: Calculate the mean of the Marks column for each group.
Step 4: Display the result.
import pandas as pd
df = pd.read_csv('students.csv')
course_average = df.groupby('Course')['Marks'].mean()
print(course_average)
Expected output:
Course
Data Analytics 83.0
Python 77.0
Web Design 85.0
Name: Marks, dtype: float64
Explanation: groupby() divides the records into groups based on the course. The mean() method calculates the average marks within each group. For Python, the average is (78 + 65 + 88) / 3 = 77.
Practice extension: Calculate the maximum marks for each course using groupby('Course')['Marks'].max().
Q6: Sort Students and Generate a Performance Report
Problem: Prepare a merit list by sorting students from highest to lowest marks. Then calculate the total fee collection and overall average marks.
Step 1: Read students.csv.
Step 2: Sort the DataFrame by Marks in descending order.
Step 3: Calculate the total fees and average marks.
Step 4: Display the report.
import pandas as pd
df = pd.read_csv('students.csv')
merit_list = df.sort_values(by='Marks', ascending=False)
print('Merit List:')
print(merit_list[['Name', 'Course', 'Marks']])
print('Total fee collection:', df['Fees'].sum())
print('Overall average marks:', df['Marks'].mean())
Expected output:
Merit List:
Name Course Marks
1 Priya Data Analytics 92
4 Karan Python 88
3 Neha Web Design 85
0 Aman Python 78
5 Simran Data Analytics 74
2 Rahul Python 65
Total fee collection: 50000
Overall average marks: 80.33333333333333
Explanation: sort_values() arranges rows based on the specified column. Setting ascending=False sorts from highest to lowest. The sum() method calculates total fees, and mean() calculates the overall average marks.
Bonus Challenge: Find Students with Unpaid or Outstanding Fees
Problem: Extend the student dataset by adding a FeeStatus column containing Paid or Pending values. Display only students whose fee status is Pending.
Solution:
df['FeeStatus'] = ['Paid', 'Pending', 'Paid', 'Pending', 'Paid', 'Pending']
pending_students = df[df['FeeStatus'] == 'Pending']
print(pending_students[['Name', 'Course', 'Fees', 'FeeStatus']])
Explanation: This exercise demonstrates how Pandas can filter administrative records, making it useful for coaching institute fee management and reporting.
Conclusion
By completing these practical exercises, you have learned to create DataFrames, filter records, import CSV files, handle missing values, group data, sort results, and calculate summary statistics. These are essential skills for data analysis with Python Pandas.
Continue practicing with larger datasets and real-world projects to strengthen your data analysis skills at Pivot Edu Unit.