Unit5 Python DataAnalysis QBank
Unit5 Python DataAnalysis QBank
UNIT 5
Python for Data Analysis
NumPy | Pandas | Matplotlib
Comprehensive Theory Question & Answer Bank
University Exam Preparation | 16-Mark Long Answer Questions
ah
✅ Key Point
This document contains detailed, university-level long-answer questions and model answers
Sh
for Unit 5: Python for Data Analysis. Each answer is structured with definition, explanation,
syntax, coded examples with output, advantages, and conclusion — suitable for 16-mark
theory examinations, viva preparation, and assignment writing.
h
ris
K
Q1. What is NumPy? Explain its features, installation, and how it differs
from Python lists. Why is NumPy preferred for scientific computing?
1. Introduction to NumPy
ah
NumPy (Numerical Python) is an open-source Python library that provides support for large,
multi-dimensional arrays and matrices, along with a collection of high-level mathematical functions to
operate on these arrays. It forms the backbone of the entire Python scientific computing ecosystem,
serving as the foundational package for libraries such as Pandas, Matplotlib, SciPy, and Scikit-Learn.
NumPy was created by Travis Oliphant in 2005, building upon the earlier Numeric library. Its core object
numerical operations.
• Contiguous Memory Allocation: All elements are stored consecutively in memory, enabling
cache-efficient access.
• Integration with C/C++/Fortran: NumPy arrays can be directly passed to routines written in
low-level languages.
• Linear Algebra, Fourier Transforms, Random Number Generation: Built-in support for advanced
mathematical operations.
• Data Type Support: Rich set of data types including int32, int64, float32, float64, complex, bool,
K
3. Installation
ah
involves Python overhead and compiled C code internally
type checking
Element-wise Operations Not supported natively (need Fully supported: e.g., array * 2
loops or list comprehensions) doubles every element
instantly
Memory Efficiency More memory — stores type Less memory — stores only
Mathematical Functions
Part of
Sh
info + value per element
import numpy as np
import time
start = [Link]()
lst_result = [x * 2 for x in lst]
print('List time:', [Link]() - start) # ~0.1 seconds
✅ Key Point
NumPy is approximately 50–100x faster than Python lists for numerical computations
because it avoids Python's interpreter overhead by executing operations in pre-compiled C
code.
6. Applications of NumPy
• Data Science and Machine Learning: Feature matrices, weight arrays in neural networks.
• Image Processing: Images are stored as 2-D or 3-D NumPy arrays (pixel values).
• Signal Processing: Fourier transforms, filtering using NumPy's FFT module.
ah
• Financial Modelling: Portfolio analysis, statistical computations on time-series data.
• Scientific Simulations: Physics, chemistry, and biology simulations.
✅ Key Point
Conclusion: NumPy is the fundamental building block for numerical computing in Python. Its
n-dimensional array object, combined with vectorised operations and memory efficiency,
Sh
makes it indispensable for any data analysis or scientific computing task.
h
ris
K
Q2. Explain the different methods of creating NumPy arrays with syntax
and examples. Cover 1-D, 2-D arrays, [Link](), [Link](), [Link](),
[Link](), and [Link]().
The most basic method of creating a NumPy array is to convert an existing Python list using [Link]().
NumPy automatically infers the data type from the provided values.
ah
import numpy as np
# Output:
# [[1. 2.]
# [3. 4.]]
[Link](shape, dtype=float) creates an array filled entirely with 0.0. Useful for initialising output arrays
before filling with computed values.
# [[0. 0. 0. 0.]
# [0. 0. 0. 0.]
# [0. 0. 0. 0.]]
# Integer zeros
z3 = [Link]((2, 3), dtype=int)
print(z3)
# Output:
# [[0 0 0]
# [0 0 0]]
ah
[Link](shape, dtype=float) creates an array filled entirely with 1.0. Commonly used as initialiser for
weight arrays in algorithms.
o1 = [Link]((2, 4))
print(o1)
# Output:
# [[1. 1. 1. 1.]
# [1. 1. 1. 1.]] Sh
4. [Link]() — Evenly Spaced Values (Step-based)
[Link](start, stop, step) creates a 1-D array with evenly spaced values from start (inclusive) to stop
h
(exclusive), incrementing by step. It behaves like Python's built-in range() but returns a NumPy array.
a1 = [Link](10) # 0 to 9
print(a1) # [0 1 2 3 4 5 6 7 8 9]
# With step
K
# Float step
a4 = [Link](0.0, 1.0, 0.25)
print(a4) # [0. 0.25 0.5 0.75]
[Link](start, stop, num) returns num evenly spaced values between start and stop (both inclusive).
Unlike arange(), you specify the number of values — not the step size. Ideal for plotting mathematical
functions.
ah
[Link](x, y)
[Link]('Sine Wave')
[Link]()
eye3 = [Link](3)
print(eye3)
Sh
[Link](N) creates an N×N 2-D array where diagonal elements are 1 and all off-diagonal elements are
# Output:
# [[1. 0. 0.]
# [0. 1. 0.]
h
# [0. 0. 1.]]
⚠️ Common Mistake
Common Mistake: [Link](1,2,3,4) raises a TypeError. The correct syntax is
[Link]([1,2,3,4]) — always pass a single list as the argument.
ah
Sh
h
ris
K
Q3. Explain Arrays and Scalars, Indexing and Slicing of NumPy Arrays
with detailed examples including 1-D and 2-D arrays and Boolean
indexing.
NumPy allows arithmetic operations to be performed between an array and a scalar (single number).
The scalar is automatically applied to every element of the array. This eliminates the need for explicit
for-loops and is called vectorisation.
ah
import numpy as np
[1. 2. 3. 4. 5.]Sh
[20 40 60 80 100]
NumPy uses zero-based indexing (same as Python lists). Negative indices count from the end of the
array.
# Modifying values
arr2d[0, 0] = 100
print(arr2d[0]) # [100 2 3]
Slicing uses the notation arr[start:stop:step]. If start is omitted, it defaults to 0; if stop is omitted, it
defaults to the end of the array. Slicing returns a view, not a copy — modifying the slice modifies the
ah
original array.
print(arr2d[0:2, 1:3])
# [[2 3]
h
# [6 7]]
Boolean indexing allows elements to be selected based on a condition. A boolean array of the same
shape as the original is generated, and only elements where the condition is True are returned.
K
# One-liner
print(marks[marks >= 75]) # [85 91 88]
# Combined conditions
print(marks[(marks > 50) & (marks < 90)]) # [72 85 67 55 88]
⚠️ Common Mistake
Important: Slicing returns a VIEW of the original array (not a copy). Changes to the slice
affect the original. To create an independent copy, use [Link]().
ah
Sh
h
ris
K
1. Array Transposition
Transposition of an array swaps its axes. For a 2-D array (matrix), transposition converts rows into
columns and columns into rows. NumPy provides two equivalent ways to transpose an array: the .T
attribute and [Link]() function.
ah
import numpy as np
# Using [Link]()
arr_T2 = [Link](arr)
print(arr_T2)
h
# [[1 4]
# [2 5]
# [3 6]]
ris
# [ 61 68 75]
# [ 95 106 117]]
Universal Functions (ufuncs) are NumPy's vectorised wrapper functions that operate element-wise on
arrays. They execute in compiled C code, avoiding Python's slow interpreter loop. Ufuncs can operate
on scalars, arrays of any shape, and support broadcasting.
ah
import numpy as np
# Trigonometric
# [0. 1. 2.] — log base 10
# Rounding
vals = [Link]([1.234, 5.678, 9.001])
ris
a = [Link]([2, 5, 8, 3])
b = [Link]([4, 1, 7, 9])
# Power
print([Link](a, 2)) # [ 4 25 64 9]
ah
print([Link](data, axis=1)) # [ 6 15 24] — row sums
print([Link](data)) # 5.0
print([Link](data)) # 2.581...
print([Link](data)) # 1
print([Link](data)) # 9
print([Link](data)) # 8 — index of max element (flat)
Sh
h
ris
K
Q5. Explain Array Input and Output in NumPy — how to save arrays to
files and load them back. Include [Link](), [Link](), [Link](), and
[Link]().
NumPy provides functions to persist arrays to disk and reload them, which is essential for saving
computed results, sharing datasets, and resuming long computations. There are two categories:
• Binary Format (.npy, .npz): Preserves data type and shape perfectly. Faster and more
ah
memory-efficient.
• Text Format (.txt, .csv): Human-readable. Useful for sharing with non-NumPy tools like Excel.
import numpy as np
print(data['array_b']) # [4 5 6]
import numpy as np
ah
4. [Link]() — Load Text/CSV Files
[Link]() is the preferred function for loading data from text files, especially CSV files. It handles
missing values, allows specifying delimiters, skipping header rows, and selecting data types.
import numpy as np
delimiter=',',
names=True,
dtype=None,
encoding='utf-8')
ah
Sh
h
ris
K
Q6. What is Pandas? Explain where Pandas is used, its key data
structures, and how it compares to NumPy. Also explain the Series data
structure with all methods of creation.
1. Introduction to Pandas
ah
Pandas (PANel DAta) is an open-source Python library built on top of NumPy that provides high-level,
easy-to-use data structures and data analysis tools. It is the most widely used library for data
manipulation, cleaning, transformation, and analysis in Python.
Pandas was created by Wes McKinney in 2008 while working at AQR Capital Management. It was
open-sourced in 2009 and has since become a cornerstone of the data science ecosystem.
•
Sh
Data Wrangling and Cleaning: Handling missing values, renaming columns, filtering rows,
converting data types.
• Exploratory Data Analysis (EDA): Summary statistics, value counts, grouping, and aggregation.
• Data Import/Export: Reading from and writing to CSV, Excel, JSON, SQL databases, Parquet,
HTML.
h
• Time Series Analysis: Resampling, rolling averages, date range generation for financial data.
• Feature Engineering: Creating new columns, encoding categorical variables for machine learning.
• Database Operations: Group By, Join, Merge — similar to SQL but in Python.
ris
4. Pandas Installation
ah
# Install Pandas
pip install pandas
# Import convention
import pandas as pd
import numpy as np
import pandas as pd
# 3 40
# dtype: int64
# Access by label
print(s2['Science']) # 92
# Access by position
print([Link][0]) # 85
import numpy as np
import pandas as pd
ah
arr = [Link]([100, 200, 300, 400])
s3 = [Link](arr, index=['Jan', 'Feb', 'Mar', 'Apr'])
print(s3)
# Jan 100
# Feb 200
# Mar 300
# Apr 400
# dtype: int32
Sh
# Note: index length must match array length
# Mismatched length raises ValueError
s4 = [Link](capitals)
print(s4)
# India New Delhi
# UK London
# Japan Tokyo
# France Paris
# dtype: object
K
print([Link]()) # 331
print([Link]()) # 66.2
print([Link]()) # 91
print([Link]()) # 38
print([Link]()) # 22.89...
# Filtering
print(marks[marks > 60])
# Alice 72
# Bob 85
# David 91
# dtype: int64
# Sorting
ah
print(marks.sort_values(ascending=False))
# David 91
# Bob 85
# Alice 72
# Charlie 45
# Eve 38
Sh
h
ris
K
1. What is a DataFrame?
A Pandas DataFrame is a two-dimensional, tabular data structure with labelled axes (rows and
columns). It can be thought of as a collection of Series objects that share the same index. Each column
in a DataFrame is a Series, and each row is identified by its index label. A DataFrame is the primary
data structure in Pandas and is the closest Python equivalent to a database table or an Excel
ah
spreadsheet.
The most common way to create a DataFrame is from a dictionary where keys become column names
and values (lists) become column data.
import pandas as pd
student_data = {
'Name':
Sh
['Alice', 'Bob', 'Charlie', 'Diana'],
'Age': [20, 22, 21, 23],
'Marks': [85, 78, 92, 88],
'Grade': ['A', 'B', 'A+', 'A']
h
}
df = [Link](student_data)
print(df)
ris
# Output:
# Name Age Marks Grade
# 0 Alice 20 85 A
# 1 Bob 22 78 B
# 2 Charlie 21 92 A+
# 3 Diana 23 88 A
# DataFrame Properties
K
records = [
{'Product': 'Laptop', 'Price': 55000, 'Qty': 10},
{'Product': 'Phone', 'Price': 25000, 'Qty': 50},
{'Product': 'Tablet', 'Price': 30000, 'Qty': 25},
]
df2 = [Link](records)
print(df2)
# Product Price Qty
# 0 Laptop 55000 10
# 1 Phone 25000 50
# 2 Tablet 30000 25
ah
4. Accessing Columns
# 3 Diana 23 88 A
# Drop a column
ah
df_dropped = [Link](columns=['Age'])
print(df_dropped.[Link]()) # ['Name', 'Marks', 'Grade', 'Percentage',
'Pass']
Sh
[Link](columns=['Percentage'], inplace=True)
Every Pandas Series and DataFrame has an associated Index object that holds the axis labels. The
Index is immutable (cannot be modified after creation) and provides fast label-based lookups, similar to
a database key. Index objects serve as both row labels and column labels.
ah
import pandas as pd
# Checking membership
print('b' in idx)
print('z' in idx)
# DataFrame indices
# True
# False
'a'
Sh
<class '[Link]'>
Reindexing creates a new object with the data conformed to a new index. If a label in the new index
was present in the old index, the value is transferred. If it was not present, NaN is placed as the value.
This is used to realign data or introduce missing value placeholders.
import pandas as pd
K
import numpy as np
# Original Series
s = [Link]([100, 200, 300, 400],
index=['Jan', 'Feb', 'Mar', 'Apr'])
print(s)
# Jan 100
# Feb 200
# Mar 300
# Apr 400
ah
# Apr 400
# May 0
# Jun 0
print(df_reindexed)
# A B
# x 1 4 NaN
# y 2 5 NaN
# z 3 6 NaN
C Sh
df_reindexed = [Link](columns=['A', 'B', 'C'])
import pandas as pd
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'Maths': [85, 78, 92, 88],
'Science': [79, 90, 85, 95],
'English': [88, 72, 80, 91]
K
})
# Drop a column
df3 = [Link](columns='English')
print([Link]()) # ['Name', 'Maths', 'Science']
📝 Important Note
The axis parameter: For rows use axis=0 (default). For columns use axis=1, OR use the
columns= keyword argument. Both [Link]('A', axis=1) and [Link](columns='A') are
equivalent.
ah
Sh
h
ris
K
Q9. Explain Selecting Entries, Data Alignment, Rank and Sort in Pandas
DataFrame with examples.
1. Selecting Entries
Pandas offers multiple methods to select specific data from a Series or DataFrame. The choice of
method depends on whether labels or integer positions are used.
import pandas as pd
ah
df = [Link]({
'Name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
'Dept': ['HR', 'IT', 'IT', 'Finance', 'HR'],
'Salary': [50000, 80000, 75000, 90000, 55000],
'Age': [28, 35, 32, 40, 27]
})
print([Link][0:3, 0:2])
# First 3 rows, first 2 columns (EXCLUSIVE end)
2. Data Alignment
Data alignment is one of Pandas' most powerful features. When performing operations between two
Series or DataFrames, Pandas automatically aligns data on their index labels before computing. If a
label exists in one object but not the other, the result at that label is NaN.
import pandas as pd
ah
# A NaN
# B 25.0
# C 45.0
# D NaN
# dtype: float64
3. Sorting
import pandas as pd
K
df = [Link]({
'Name': ['Charlie', 'Alice', 'Eve', 'Bob', 'Diana'],
'Score': [92, 85, 78, 90, 88]
})
# 0 Charlie 92
# Sort descending
print(df.sort_values('Score', ascending=False))
# Sort by index
print(df.sort_index())
print(df.sort_index(ascending=False))
ah
4. Ranking
import pandas as pd
# 4 4.5
# 2 1.0
# 3 5.0
# 4 4.0
ah
Sh
h
ris
K
Descriptive statistics provide a concise summary of the central tendency, dispersion, and shape of a
dataset. Pandas provides these as built-in methods that can operate column-wise (axis=0) or row-wise
(axis=1).
ah
import pandas as pd
df = [Link]({
'Maths': [22, 21, 14, 20, 23, 22, 23, 24, 12, 15, 18, 17],
'Science': [21, 20, 19, 17, 15, 18, 19, 22, 25, 22, 21, 18],
'English': [21, 24, 23, 19, 15, 13, 22, 21, 23, 22, 23, 20],
})
# mean
# std
Maths
# count 12.000
19.25
3.84
Science
12.000
19.75
2.80
Sh
English
12.000
20.5
3.17
# min 12.00 15.00 13.00
# 25% 17.00 18.25 19.25
# 50% 20.50 19.50 21.00
h
# 75% 22.00 21.75 22.75
# max 24.00 25.00 24.00
ris
# Cumulative operations
print(df['Maths'].cumsum()) # Running total
print(df['Maths'].cumprod()) # Running product
3. GroupBy — Split-Apply-Combine
GroupBy is one of the most powerful Pandas operations. It works in three stages: Split the data into
groups based on a criterion, Apply a function to each group independently, and Combine the results
into a new object. This is directly analogous to SQL's GROUP BY clause.
ah
import pandas as pd
df = [Link]({
'Name': ['Raman','Raman','Raman','Zuhaire','Zuhaire','Zuhaire'],
'UT': [1, 2, 3, 1, 2, 3],
'Maths':[22, 21, 14, 20, 23, 22],
'Science':[21, 20, 19, 17, 15, 18]
})
print(grouped['Maths'].mean())
# Name
# Raman 19.000000
Sh
# Group by Name, compute average marks per student
grouped = [Link]('Name')
# Zuhaire 21.666667
# Name: Maths, dtype: float64
h
# Aggregate multiple columns
print(grouped[['Maths', 'Science']].mean())
# Name Maths Science
# Raman 19.000000 20.000000
ris
Missing data (also called null values or NA values) occurs when no value is stored for a particular
observation in a variable. In Pandas, missing values are represented as NaN (Not a Number) for
numeric columns and None or NaT (Not a Time) for datetime columns. Missing data is extremely
common in real-world datasets due to data entry errors, sensor failures, optional form fields, or merging
of incomplete records.
ah
Handling missing data correctly is critical because:
• Statistical functions like mean() and std() produce incorrect results when NaN values are present
without proper handling.
• Machine learning algorithms generally cannot handle NaN values and will raise errors.
• Ignoring missing values may introduce bias in analysis results.
import pandas as pd
import numpy as np
Sh
df = [Link]({
'Name': ['Alice', 'Bob', [Link], 'Diana'],
h
'Maths': [85, [Link], 92, 88],
'Science': [79, 90, 85, [Link]],
})
ris
# Percentage missing
print(([Link]().sum() / len(df)) * 100)
# Name 25.0
# Maths 25.0
# Science 25.0
dropna() removes rows (or columns) that contain any NaN values. The 'how' parameter controls
behaviour: 'any' drops a row if ANY value is NaN (default), while 'all' drops a row only if ALL values are
NaN.
ah
import pandas as pd
import numpy as np
df = [Link]({
'Name': ['Alice', 'Bob', [Link], 'Diana'],
'Maths': [85, [Link], 92, 88],
'Science': [79, 90, 85, [Link]],
})
print([Link](thresh=2))
import pandas as pd
import numpy as np
df = [Link]({
'Maths': [85, [Link], 92, 88, [Link]],
ah
print(df_filled)
# Maths NaN replaced with mean of 85,92,88 = 88.33
A hierarchical index (also called MultiIndex) allows Pandas to store and manipulate data with an
arbitrary number of index levels. It provides a way to work with higher-dimensional data (more than 2
dimensions) in a lower-dimensional data structure like a Series or DataFrame. This is particularly useful
for representing data that has natural group structure, such as student marks across multiple tests and
multiple subjects.
ah
2. Creating a MultiIndex Series
import pandas as pd
])
('Raman', 'Maths'),
('Raman', 'Science'),
('Zuhaire', 'Maths'),
('Zuhaire', 'Science'),
Sh
s = [Link]([85, 90, 78, 88], index=index)
print(s)
# Raman Maths 85
h
# Science 90
# Zuhaire Maths 78
# Science 88
# dtype: int64
ris
import pandas as pd
], names=['Name', 'Test'])
df = [Link]({
'Maths': [22, 21, 14, 20, 23, 22],
'Science': [21, 20, 19, 17, 15, 18],
}, index=idx)
print(df)
# Name Test Maths Science
# Raman UT1 22 21
# UT2 21 20
# UT3 14 19
# Zuhaire UT1 20 17
# UT2 23 15
ah
# UT3 22 18
# Chennai 11
ah
Sh
h
ris
K
1. Introduction to Matplotlib
ah
Matplotlib is a comprehensive, open-source Python library for creating static, animated, and interactive
visualisations. It was created by John D. Hunter in 2003 and is now maintained by a large community of
developers. Matplotlib is the foundational plotting library in the Python ecosystem, and most
higher-level libraries such as Seaborn, Pandas plotting, and Plotly are built on top of it.
The key module used for plotting is [Link], which provides a MATLAB-like interface for
2. Installation
# Install Matplotlib
Sh
creating charts. By convention, it is imported as plt.
# Data
date = ['25/12', '26/12', '27/12', '28/12']
temp = [8.5, 10.5, 6.8, 9.2]
ah
[Link]('Date')
[Link]('Temperature (°C)')
[Link]('Daily Maximum Temperature')
[Link](True)
# Display
[Link]()
Sh
Explanation of output: The plot() function by default connects data points with a solid blue line. The
x-axis shows dates and the y-axis shows temperatures. The grid makes it easier to read values.
height = [121.9, 124.5, 129.5, 134.6, 139.7, 147.3, 152.4, 157.5, 162.6]
weight = [19.7, 21.3, 23.5, 25.9, 28.5, 32.1, 35.7, 39.6, 43.2]
[Link](weight, height,
color='green',
linestyle='dashdot',
linewidth=2,
marker='*',
markersize=10,
label='Height vs Weight')
[Link]('Weight (kg)')
[Link]('Height (cm)')
[Link]('Average Height vs Weight (Age 8-16)')
[Link]()
ah
[Link](True)
[Link]()
6. Saving a Figure
[Link]([1,2,3], [4,5,6])
Sh
# Save the figure to a file instead of displaying
Q14. Explain Bar Charts, Histograms, Scatter Plots, and Pie Charts in
Matplotlib with complete Python code and output explanation for each.
A bar chart displays categorical data using rectangular bars whose heights or lengths are proportional
to the values they represent. It is used to compare values across different categories.
ah
subjects = ['Maths', 'Science', 'English', 'History', 'Geography']
marks = [88, 75, 91, 69, 82]
[Link]('Subject')
[Link]('Marks')
[Link]('Student Marks by Subject')
[Link](0, 100) # Set Y-axis range
[Link](range(0, 101, 10))
Sh
[Link](axis='y', linestyle='--', alpha=0.7)
[Link]()
h
# Horizontal bar chart
[Link](subjects, marks, color='steelblue')
[Link]('Marks')
ris
Output Explanation: Each subject is represented by a coloured bar. The height of the bar equals the
marks obtained. English has the tallest bar (91), indicating the highest score. The Y-axis grid makes it
easy to read exact values.
K
2. Histogram — [Link]()
A histogram shows the distribution of a continuous numerical variable by dividing the data into bins
(intervals) and counting how many values fall in each bin. Unlike a bar chart, a histogram has no gaps
between bars (unless specified).
[Link](marks,
bins=10,
color='steelblue',
edgecolor='white',
alpha=0.8)
[Link]('Marks')
[Link]('Frequency (Number of Students)')
[Link]('Distribution of Student Marks')
ah
[Link]([Link](), color='red', linestyle='--',
linewidth=2, label=f'Mean: {[Link]():.1f}')
[Link]()
[Link]()
Output Explanation: The histogram shows a bell-shaped curve centred around 65 (the mean), as
A scatter plot displays the relationship between two continuous variables. Each data point is
represented as a dot. Scatter plots are used to detect correlations, clusters, and outliers.
h
import [Link] as plt
import numpy as np
ris
[Link](study_hours, exam_scores,
color='darkred',
marker='o',
s=80, # marker size
K
alpha=0.8,
label='Students')
Output Explanation: The scatter plot shows a clear positive correlation — students who study more
hours tend to score higher. Points in the upper right indicate high-performers. An outlier (student
studying 11 hours with only 87%) is also visible.
ah
4. Pie Chart — [Link]()
A pie chart displays data as slices of a circle, where each slice's area is proportional to its value. Pie
charts are best used when showing parts of a whole with 5 or fewer categories.
departments
headcount
explode
=
=
=
[40, 25, 15, 10, 10]
Sh
['Engineering', 'Marketing', 'HR', 'Finance', 'Operations']
[Link](headcount,
h
labels=departments,
autopct='%1.1f%%', # Show percentage inside slices
startangle=90, # Start from top
explode=explode,
ris
colors=colors,
shadow=True)
Output Explanation: Each slice represents one department. Engineering (40%) has the largest slice.
The explode parameter separates the Engineering slice slightly for emphasis. Percentages are
displayed inside each slice via autopct.
Q15. Explain Multiple Plots, Subplots, and the Pandas Plot Function with
examples showing how Pandas integrates with Matplotlib for data
visualisation.
Multiple data series can be plotted on the same axes by calling [Link]() multiple times before
[Link](). A legend is essential to distinguish the lines.
ah
import [Link] as plt
import numpy as np
linestyle='dashed')
[Link](-2, 2)
[Link]('y')
Sh
[Link](x, [Link](x), color='green', label='tan(x)', linewidth=1,
[Link]('Trigonometric Functions')
[Link](loc='upper right')
[Link](True, alpha=0.4)
[Link](y=0, color='black', linewidth=0.8) # X-axis line
h
[Link]()
2. Subplots — [Link]()
ris
Subplots allow multiple charts to be displayed in a grid layout within a single figure. [Link](nrows,
ncols, index) specifies the grid size and which subplot to draw next.
# Subplot 1 — Line
[Link](2, 2, 1)
[Link](x, [Link](x), 'b-')
[Link]('Line Plot: sin(x)')
[Link](True)
# Subplot 2 — Scatter
[Link](2, 2, 2)
[Link]([Link](50), [Link](50), color='red')
[Link]('Scatter Plot')
# Subplot 3 — Bar
[Link](2, 2, 3)
cats = ['A', 'B', 'C', 'D']
vals = [3, 7, 5, 9]
[Link](cats, vals, color='green')
[Link]('Bar Chart')
# Subplot 4 — Histogram
[Link](2, 2, 4)
ah
data = [Link](200)
[Link](data, bins=15, color='purple', edgecolor='white')
[Link]('Histogram')
import pandas as pd
h
import [Link] as plt
xlabel='Month',
ylabel='Amount (₹ thousands)',
figsize=(8, 5))
[Link]()
# Bar plot
[Link](kind='bar', figsize=(8, 5), color=['steelblue', 'tomato'])
[Link]('Sales vs Expenses — Bar Chart')
[Link](rotation=0)
[Link]()
import numpy as np
marks_df = [Link]({'Maths': [Link](40,100,50),
'Science': [Link](50,100,50)})
marks_df.plot(kind='hist', bins=10, alpha=0.7,
title='Marks Distribution')
[Link]()
ah
Plot Type Pandas kind= Matplotlib Function Use Case
Line kind='line' [Link]() Trends over time
Bar (vertical) kind='bar' [Link]() Category
Bar (horizontal)
Histogram
Scatter
kind='barh'
kind='hist'
kind='scatter'
Sh [Link]()
[Link]()
[Link]()
comparisons
Long category names
Distribution of data
Relationships
between variables
Pie kind='pie' [Link]() Parts of a whole
Box plot kind='box' [Link]() Data spread,
h
quartiles, outliers
Area kind='area' plt.fill_between() Cumulative quantities
over time
ris
K
ah
Matplotlib Mathematical Plotting Data visualisation — Figure, Axes
Library charts, graphs, plots
NumPy Indexing
NumPy ufuncs
Sh
[Link](), [Link]()
arr[i], arr[r,c],
arr[start:stop:step], boolean
mask
[Link](), [Link](), [Link](),
Slices return views, not copies
✅ Key Point
For university examinations: Every 16-mark answer should follow the structure — (1)
Definition/Introduction (2) Syntax (3) Detailed Explanation (4) Coded Examples (5) Output
with explanation (6) Advantages/Applications (7) Conclusion. Presenting comparison tables
and labelled code output significantly improves marks.
ah
— End of Unit 5: Python for Data Analysis Question Bank —
Sh
h
ris
K