Set B - Question 2
2. a) Consider the following monthly sales data:
Assume:
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [12000, 15000, 18000, 14000, 22000, 26000]
Answer the following: i. Create a line plot representing monthly sales. ii. Add an appropriate title and labels for both axes. iii. Add grid lines and a legend to the plot. iv. Identify the month with the highest sales from the visualization. v. Explain why a line plot is suitable for this dataset.
Answer
i, ii, & iii. Python Code for Custom Line Plot
import matplotlib.pyplot as plt
# Dataset
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [12000, 15000, 18000, 14000, 22000, 26000]
# Set up figure
plt.figure(figsize=(7, 4.5))
# i. Plot line chart with custom color, marker, and label
plt.plot(months, sales, color='forestgreen', linestyle='-', linewidth=2, marker='o', label='Monthly Performance')
# ii. Add labels and titles
plt.title('Monthly Sales Revenue Analysis (H1)', fontsize=12, fontweight='bold', pad=12)
plt.xlabel('Month', fontsize=10)
plt.ylabel('Sales Revenue ($)', fontsize=10)
# iii. Add grid lines and legend
plt.grid(True, which='both', linestyle='--', alpha=0.5)
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
iv. Identify the Month with the Highest Sales
- Based on the plotted values, June shows the highest sales of $26,000 (represented by the peak coordinate point on the line).
v. Why a Line Plot is Suitable
- Temporal Progression: A line plot represents continuous progression over sequential intervals of time (January through June), showing fluctuations, momentum, and growth trends effortlessly.
- Slope Steeps: The steepness of the connecting segments highlights the rate of sales change from month to month (e.g., steep increase from April to June).
2. b) Explain Matplotlib and its role in data visualization. Describe any five types of plots and their applications with suitable examples.
Answer
What is Matplotlib?
Matplotlib is a robust, low-level charting and plotting library in Python. It provides an object-oriented API for building static, animated, and interactive visualizations.
Role in Data Visualization
- EDA Checkpoint: Allows analysts to quickly explore data range, skewness, and outliers visually.
- Publication-Quality Figures: Gives engineers exact and precise control over axes, ticks, grids, colors, and markers for reports.
Five Types of Plots and Their Applications
-
Line Plot
- Application: Tracking trends, progression, or changes over continuous timelines.
- Example: Showing daily stock price fluctuations.
-
Bar Chart
- Application: Comparing discrete categories or groups.
- Example: Comparing total sales figures across different regional branches.
-
Scatter Plot
- Application: Investigating correlations, clusters, or distributions between two continuous variables.
- Example: Analyzing how advertising cost impacts product sales volume.
-
Histogram
- Application: Showing the frequency distribution and shape of a single numerical variable.
- Example: Checking student test score distribution (e.g., normal or skewed).
-
Box Plot
- Application: Depicting the five-number summary (minimum, , median, , maximum) and highlighting statistical outliers.
- Example: Comparing salary spreads across company departments.
2. c) A dataset contains employee records with missing values, duplicate records, and incorrect data types. Consider the following DataFrame:
data = {
"Name": ["Alice", "Bob", "Charlie", "Alice", "David", None],
"Age": [25, None, 30, 25, 45, 35],
"Salary": ["50000", "60000", "70000", "50000", "80000", "55000"]
}
Answer the following: i. Create a DataFrame and inspect its structure using appropriate functions. ii. Identify the missing value in the Age column and handle it appropriately. iii. Identify and remove the duplicate record. iv. Convert the Salary column from string/object type to a numerical type. v. Display the cleaned DataFrame and explain why each cleaning step is necessary.
Answer
i, ii, iii, iv & v. Complete Python Program
import pandas as pd
import numpy as np
# i. Create and inspect DataFrame
print("--- i. Creating and Inspecting DataFrame ---")
data = {
"Name": ["Alice", "Bob", "Charlie", "Alice", "David", None],
"Age": [25, None, 30, 25, 45, 35],
"Salary": ["50000", "60000", "70000", "50000", "80000", "55000"]
}
df = pd.DataFrame(data)
# Print structural information
df.info()
print("\nInitial DataFrame:\n", df)
# ii. Identify missing values and handle Age column
print("\n--- ii. Handling Missing Values ---")
print("Null count before:\n", df.isnull().sum())
# Age is numerical, so we impute with median age to prevent skewing the distribution
age_median = df["Age"].median()
df["Age"] = df["Age"].fillna(age_median)
# For name (categorical), replace null with "Unknown"
df["Name"] = df["Name"].fillna("Unknown")
# iii. Identify and remove duplicates
print("\n--- iii. Removing Duplicates ---")
# Keep first occurrence, drop matching rows
df = df.drop_duplicates(keep="first").reset_index(drop=True)
# iv. Convert Salary from string to numerical
print("\n--- iv. Data Type Conversion ---")
df["Salary"] = pd.to_numeric(df["Salary"])
# v. Display Cleaned DataFrame
print("\n--- v. Cleaned DataFrame ---")
print(df)
Why each cleaning step is necessary:
- Handling Missing Values: Missing values can break downstream computations or machine learning models. Filling
Agewith the median () handles nulls safely without introducing bias. - Removing Duplicates: Redundant copies of records skew mathematical indicators (like mean, count, or totals). Dropping duplicates prevents over-counting of transactions or elements.
- Converting Salary Column Type: Python treats quoted numbers as text objects, preventing any mathematical calculations (like calculating averages or sums). Converting to numeric type is required for mathematical computation.