CS Pathfinder Logo CS Pathfinder

Unit 5 · Advanced Topics

Practice Programs using NumPy, Pandas and Matplotlib

This chapter provides hands-on practice programs combining NumPy for numerical computing, Pandas for data manipulation, and Matplotlib for visualization — the complete Python data science toolkit.

Practice Programs

Program 1: NumPy Array Operations

Problem: Create a NumPy array, perform slicing, reshaping, and mathematical operations.

import numpy as np

# Create array
arr = np.array([10, 20, 30, 40, 50, 60])
print("Original:", arr)

# Slicing
print("First 3:", arr[:3])
print("Last 2:", arr[-2:])

# Reshape to 2x3 matrix
matrix = arr.reshape(2, 3)
print("\nReshaped (2x3):\n", matrix)

# Mathematical operations
print("\nSum:", np.sum(arr))
print("Mean:", np.mean(arr))
print("Max:", np.max(arr))
print("Std Dev:", round(np.std(arr), 2))

# Element-wise operations
print("\nDoubled:", arr * 2)
print("Squared:", arr ** 2)

Expected Output

Original: [10 20 30 40 50 60]
First 3: [10 20 30]
Last 2: [50 60]
Reshaped (2x3):
 [[10 20 30]
 [40 50 60]]
Sum: 210
Mean: 35.0
Max: 60
Std Dev: 17.08
Doubled: [ 20  40  60  80 100 120]
Squared: [ 100  400  900 1600 2500 3600]

Explanation: This program demonstrates array creation, slicing to extract sub-arrays, reshape to change dimensions, statistical functions (sum, mean, max, std), and element-wise arithmetic without loops.

Program 2: Student Marks DataFrame

Problem: Create a student DataFrame, filter top scorers, sort by marks, and compute class average.

import pandas as pd

# Create DataFrame
data = {
    "Name":  ["Amit", "Priya", "Rahul", "Sneha", "Vikram"],
    "Math":  [85, 92, 78, 95, 88],
    "Science": [80, 88, 72, 91, 85],
    "English": [75, 90, 85, 88, 80]
}

df = pd.DataFrame(data)

# Add Total and Average columns
df["Total"] = df["Math"] + df["Science"] + df["English"]
df["Average"] = df["Total"] / 3

print("=== Student Records ===")
print(df.to_string(index=False))

# Top 3 students by average
print("\n=== Top 3 Students ===")
top3 = df.nlargest(3, "Average")
print(top3[["Name", "Average"]].to_string(index=False))

# Class statistics
print("\n=== Class Statistics ===")
for subj in ["Math", "Science", "English"]:
    print(f"{subj}: Avg={df[subj].mean():.1f}, Max={df[subj].max()}, Min={df[subj].min()}")

Expected Output

=== Student Records ===
   Name  Math  Science  English  Total    Average
  Amit    85       80       75    240  80.000000
 Priya    92       88       90    270  90.000000
 Rahul    78       72       85    235  78.333333
 Sneha    95       91       88    274  91.333333
Vikram    88       85       80    253  84.333333

=== Top 3 Students ===
   Name   Average
 Sneha  91.333333
 Priya  90.000000
Vikram  84.333333

=== Class Statistics ===
Math: Avg=87.6, Max=95, Min=78
Science: Avg=83.2, Max=91, Min=72
English: Avg=83.6, Max=90, Min=75

Program 3: CSV Data Analysis with Pandas

Problem: Read a CSV file, display summary statistics, filter data, and export filtered results.

import pandas as pd

# Assume CSV has columns: Name, Age, Department, Salary
df = pd.read_csv("employees.csv")

# Basic inspection
print("Shape:", df.shape)
print("\nInfo:")
df.info()

# Statistical summary
print("\n=== Statistics ===")
print(df.describe())

# Filter: IT department employees
it_employees = df[df["Department"] == "IT"]
print("\n=== IT Department ===")
print(it_employees)

# Department-wise average salary
print("\n=== Dept-wise Avg Salary ===")
print(df.groupby("Department")["Salary"].mean())

# Export filtered data
it_employees.to_csv("it_employees.csv", index=False)
print("\nIT employees exported successfully!")

Program 4: Line Plot — Temperature Data

Problem: Plot weekly temperature data for two cities with proper labels and legend.

import matplotlib.pyplot as plt

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
delhi = [35, 37, 39, 38, 36, 34, 33]
mumbai = [30, 31, 33, 32, 31, 30, 29]

plt.figure(figsize=(10, 6))
plt.plot(days, delhi, "ro-", linewidth=2, markersize=8, label="Delhi")
plt.plot(days, mumbai, "bs--", linewidth=2, markersize=8, label="Mumbai")

plt.title("Weekly Temperature Comparison", fontsize=16)
plt.xlabel("Day", fontsize=12)
plt.ylabel("Temperature (°C)", fontsize=12)
plt.legend(fontsize=12)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig("temperature_chart.png", dpi=150)
plt.show()

Explanation: Two line plots on the same axes for comparison. Markers (o, s) differentiate cities. tight_layout() prevents label clipping. savefig() exports the plot.

Program 5: Bar Chart — Student Scores

Problem: Create a grouped bar chart comparing marks of students in three subjects.

import matplotlib.pyplot as plt
import numpy as np

names = ["Amit", "Priya", "Rahul", "Sneha"]
math = [85, 92, 78, 95]
science = [80, 88, 72, 91]
english = [75, 90, 85, 88]

x = np.arange(len(names))
width = 0.25

plt.figure(figsize=(10, 6))
plt.bar(x - width, math, width, label="Math", color="skyblue")
plt.bar(x, science, width, label="Science", color="salmon")
plt.bar(x + width, english, width, label="English", color="lightgreen")

plt.title("Student Marks Comparison", fontsize=16)
plt.xlabel("Students")
plt.ylabel("Marks")
plt.xticks(x, names)
plt.legend()
plt.ylim(0, 100)
plt.tight_layout()
plt.show()

Program 6: Scatter Plot — Correlation

Problem: Plot the relationship between hours studied and marks obtained using a scatter plot.

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
marks = np.array([15, 25, 40, 50, 62, 70, 78, 85, 90, 98])

# Trend line
z = np.polyfit(hours, marks, 1)
p = np.poly1d(z)

plt.figure(figsize=(8, 6))
plt.scatter(hours, marks, color="crimson", s=120,
            edgecolor="black", zorder=5)
plt.plot(hours, p(hours), "b--", linewidth=2, label="Trend Line")

plt.title("Hours Studied vs Marks", fontsize=16)
plt.xlabel("Hours Studied")
plt.ylabel("Marks Obtained")
plt.grid(True, alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()

Program 7: Histogram — Marks Distribution

Problem: Generate and visualize the distribution of student marks using a histogram.

import matplotlib.pyplot as plt
import numpy as np

# Generate 200 student marks between 20 and 100
np.random.seed(10)
marks = np.random.normal(loc=65, scale=15, size=200)
marks = np.clip(marks, 20, 100)

plt.figure(figsize=(10, 6))
plt.hist(marks, bins=10, color="steelblue",
         edgecolor="black", alpha=0.8)

plt.axvline(np.mean(marks), color="red", linestyle="--",
            linewidth=2, label=f"Mean: {np.mean(marks):.1f}")
plt.axvline(np.median(marks), color="green", linestyle="-.",
            linewidth=2, label=f"Median: {np.median(marks):.1f}")

plt.title("Marks Distribution of 200 Students", fontsize=16)
plt.xlabel("Marks")
plt.ylabel("Number of Students")
plt.legend()
plt.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()

Explanation: np.random.normal() generates marks following a normal distribution centered at 65. The histogram shows frequency per bin. Red dashed line shows the mean; green dash-dot line shows the median.

University Exam Tip

University practical exams often ask to write programs using Pandas (read CSV, filter, sort, groupby) and Matplotlib (plot bar chart, histogram, pie chart). Practice all 7 programs above — they cover the most commonly asked patterns. Always include comments and expected output in your answer.

Key Points

NumPy: Use array(), reshape(), sum(), mean(), std() for numerical operations.

Pandas: Use DataFrame(), read_csv(), groupby(), nlargest() for data manipulation.

Matplotlib: Use plot(), bar(), hist(), scatter(), pie() for visualization.

Always use plt.title(), plt.xlabel(), plt.ylabel(), plt.legend() for proper charts.

Combine all three libraries: NumPy for data generation, Pandas for processing, Matplotlib for plotting.

Practice writing code by hand — university exams are typically pen-and-paper based.

Summary

These 7 practice programs cover the most important use cases of NumPy, Pandas, and Matplotlib. Mastering these patterns will prepare you for university practical exams, competitive coding, and real-world data analysis tasks.

Python Programming Handwritten Notes

Master Python Programming with Easy Handwritten Notes – Perfect for Interviews, Placements, GATE & Exams.