0% found this document useful (0 votes)
3 views50 pages

Unit5 Python DataAnalysis QBank

Uploaded by

kocos91092
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views50 pages

Unit5 Python DataAnalysis QBank

Uploaded by

kocos91092
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit 5: Python for Data AnalysisUniversity Exam Question Bank

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

NumPy | Pandas | Matplotlib — Page 1


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

SECTION A — PART I: NUMPY

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.

2. Key Features of NumPy


Sh
is the ndarray (n-dimensional array), which is orders of magnitude faster than Python's native lists for

•​ N-Dimensional Array Object (ndarray): Efficient storage of homogeneous data in


multi-dimensional arrays.
•​ Broadcasting: Allows arithmetic operations between arrays of different shapes without explicit
h
looping.
•​ Universal Functions (ufuncs): Vectorised mathematical operations that work element-wise on
arrays.
ris

•​ 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

and string (Unicode).

3. Installation

# Install NumPy using pip


pip install numpy

# Import NumPy in Python (convention: alias 'np')


import numpy as np

NumPy | Pandas | Matplotlib — Page 2


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

4. NumPy Array vs Python List — Comparison Table

Feature Python List NumPy Array (ndarray)


Data Types Can contain mixed types (int, All elements must be of the
str, float, objects) same data type
(homogeneous)
Memory Layout Non-contiguous: each element Contiguous: elements stored
is a Python object stored side-by-side in memory —
separately much faster access
Speed Slower — each operation Much faster — operations use

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

Requires importing math


module and iterating manually

Core Python (built-in)


raw values without type
overhead per element
Hundreds of built-in ufuncs:
[Link](), [Link](), [Link](),
etc.
NumPy library (must be
installed and imported)
Multi-dimensional Achieved using nested lists; Native ndarray supports 1-D,
h
awkward to operate on 2-D, n-D with shape/reshape
utilities
ris

5. Demonstration — Why NumPy is Faster

import numpy as np
import time

# Python list operation


lst = list(range(1000000))
K

start = [Link]()
lst_result = [x * 2 for x in lst]
print('List time:', [Link]() - start) # ~0.1 seconds

# NumPy array operation


arr = [Link](1000000)
start = [Link]()
arr_result = arr * 2
print('NumPy time:', [Link]() - start) # ~0.001 seconds (100x faster)

NumPy | Pandas | Matplotlib — Page 3


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

✅ 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

NumPy | Pandas | Matplotlib — Page 4


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

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

1. Creating Arrays from Python Lists/Nested Lists

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

# 1-D Array from a list


arr1 = [Link]([10, 20, 30, 40, 50])
print(arr1) # Output: [10 20 30 40 50]
print([Link]) # Output: 1 (one dimension)
print([Link]) # Output: (5,) (5 elements, 1 axis)
print([Link]) # Output: int64

# 2-D Array from nested lists


Sh
arr2 = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr2)
# Output:
# [[1 2 3]
# [4 5 6]
# [7 8 9]]
print([Link]) # Output: (3, 3) → 3 rows, 3 columns
h
# Specifying dtype explicitly
arr3 = [Link]([[1, 2], [3, 4]], dtype=float)
print(arr3)
ris

# Output:
# [[1. 2.]
# [3. 4.]]

2. [Link]() — Array of All Zeros


K

[Link](shape, dtype=float) creates an array filled entirely with 0.0. Useful for initialising output arrays
before filling with computed values.

# 1-D array of zeros


z1 = [Link](5)
print(z1) # Output: [0. 0. 0. 0. 0.]

# 2-D array of zeros (3 rows, 4 columns)


z2 = [Link]((3, 4))
print(z2)
# Output:

NumPy | Pandas | Matplotlib — Page 5


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# [[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]]

3. [Link]() — Array of All Ones

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.

# Basic usage — integers


ris

a1 = [Link](10) # 0 to 9
print(a1) # [0 1 2 3 4 5 6 7 8 9]

# With start and stop


a2 = [Link](5, 15) # 5 to 14
print(a2) # [ 5 6 7 8 9 10 11 12 13 14]

# With step
K

a3 = [Link](0, 20, 4) # 0 to 19, step 4


print(a3) # [ 0 4 8 12 16]

# Float step
a4 = [Link](0.0, 1.0, 0.25)
print(a4) # [0. 0.25 0.5 0.75]

5. [Link]() — Evenly Spaced Values (Count-based)

NumPy | Pandas | Matplotlib — Page 6


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

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

# 5 values from 0 to 1 inclusive


l1 = [Link](0, 1, 5)
print(l1) # [0. 0.25 0.5 0.75 1. ]

# 100 values from 0 to 2π for plotting a sine wave


import numpy as np
import [Link] as plt
x = [Link](0, 2 * [Link], 100)
y = [Link](x)

ah
[Link](x, y)
[Link]('Sine Wave')
[Link]()

6. [Link]() — Identity Matrix

0. Used extensively in linear algebra.

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

7. [Link] — Random Arrays


ris

# Random floats between 0 and 1


r1 = [Link](3, 3)

# Random integers between 1 and 100


r2 = [Link](1, 100, size=(4,))
K

print(r2) # e.g., [47 83 12 65]

# Normal distribution (mean=0, std=1)


r3 = [Link](2, 3)

8. Important Array Attributes

Attribute Description Example Output


ndim Number of dimensions (axes) [Link] → 2

NumPy | Pandas | Matplotlib — Page 7


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

shape Tuple of array dimensions [Link] → (3, 3)


(rows, cols)
size Total number of elements [Link] → 9
dtype Data type of elements [Link] → float64
itemsize Size in bytes of each element [Link] → 8 (float64)

⚠️ 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

NumPy | Pandas | Matplotlib — Page 8


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

Q3. Explain Arrays and Scalars, Indexing and Slicing of NumPy Arrays
with detailed examples including 1-D and 2-D arrays and Boolean
indexing.

1. Arrays and Scalars — Arithmetic Operations

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

arr = [Link]([10, 20, 30, 40, 50])

# Scalar operations — applied to every element


print(arr + 5) # [15 25 35 45 55]
print(arr - 3)
print(arr * 2)
print(arr / 10)
print(arr ** 2)
print(arr % 3)
#
#
#
#
#
[ 7 17 27 37 47]

[1. 2. 3. 4. 5.]Sh
[20 40 60 80 100]

[ 100 400 900 1600 2500]


[1 2 0 1 2]

# Element-wise operations between two arrays


a = [Link]([1, 2, 3])
b = [Link]([10, 20, 30])
print(a + b) # [11 22 33]
h
print(a * b) # [10 40 90]
print(b / a) # [10. 10. 10.]
ris

2. Indexing — Accessing Single Elements

NumPy uses zero-based indexing (same as Python lists). Negative indices count from the end of the
array.

arr1d = [Link]([5, 10, 15, 20, 25])


K

print(arr1d[0]) # 5 (first element)


print(arr1d[2]) # 15 (third element)
print(arr1d[-1]) # 25 (last element)
print(arr1d[-2]) # 20 (second from last)

# 2-D Array Indexing → arr[row, col]


arr2d = [Link]([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

print(arr2d[0, 0]) # 1 (row 0, col 0)

NumPy | Pandas | Matplotlib — Page 9


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

print(arr2d[1, 2]) # 6 (row 1, col 2)


print(arr2d[2, -1]) # 9 (row 2, last col)

# Modifying values
arr2d[0, 0] = 100
print(arr2d[0]) # [100 2 3]

3. Slicing — Accessing Ranges of Elements

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.

arr = [Link]([0, 10, 20, 30, 40, 50, 60, 70])

print(arr[2:5]) # [20 30 40] → indices 2, 3, 4


print(arr[:4]) # [ 0 10 20 30] → first 4 elements
print(arr[5:]) # [50 60 70] → from index 5 to end
print(arr[::2])
print(arr[::-1])
#
#
[ 0
[70
20
60
Sh
40 60] → every 2nd element
50 40 30 20 10 0] → reversed

# 2-D Slicing → arr[row_slice, col_slice]


arr2d = [Link]([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])

print(arr2d[0:2, 1:3])
# [[2 3]
h
# [6 7]]

print(arr2d[:, 0]) # [1 5 9] → entire first column


print(arr2d[1, :]) # [5 6 7 8] → entire second row
ris

4. Boolean (Fancy) Indexing

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

marks = [Link]([72, 85, 45, 91, 38, 67, 55, 88])

# Create a boolean mask


mask = marks > 60
print(mask)
# [True True False True False True False True]

# Apply mask to get passing marks


print(marks[mask]) # [72 85 91 67 88]

NumPy | Pandas | Matplotlib — Page 10


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# 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

NumPy | Pandas | Matplotlib — Page 11


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

Q4. Explain Array Transposition and Universal Array Functions (ufuncs)


in NumPy with examples.

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

# Original 2-D array (2 rows, 3 columns)


arr = [Link]([[1, 2, 3],
[4, 5, 6]])
print('Original shape:', [Link]) # (2, 3)

# Transposition using .T attribute


arr_T = arr.T
print('Transposed shape:', arr_T.shape)
print(arr_T)
# [[1 4]
# [2 5]
# [3 6]]
Sh # (3, 2)

# Using [Link]()
arr_T2 = [Link](arr)
print(arr_T2)
h
# [[1 4]
# [2 5]
# [3 6]]
ris

# Practical: Matrix multiplication requires compatible shapes


A = [Link]([[1, 2], [3, 4], [5, 6]]) # shape (3, 2)
B = [Link]([[7, 8, 9], [10, 11, 12]]) # shape (2, 3)
result = [Link](A, B)
print([Link]) # (3, 3)
print(result)
# [[ 27 30 33]
K

# [ 61 68 75]
# [ 95 106 117]]

# Computing A^T * A (common in statistics: covariance matrices)


C = [Link]([[1, 2, 3], [4, 5, 6]])
print([Link](C.T, C))
# [[17 22 27]
# [22 29 36]
# [27 36 45]]

2. Universal Array Functions (ufuncs)

NumPy | Pandas | Matplotlib — Page 12


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

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.

There are two categories of ufuncs:


•​ Unary ufuncs: Operate on a single input array (e.g., [Link], [Link], [Link], [Link]).
•​ Binary ufuncs: Operate on two input arrays element-wise (e.g., [Link], [Link], [Link]).

3. Common Unary ufuncs

ah
import numpy as np

arr = [Link]([1, 4, 9, 16, 25])

print([Link](arr)) # [1. 2. 3. 4. 5.] — square root


print([Link]([Link]([-3, -1, 0, 4]))) # [3 1 0 4] — absolute value

# Exponential and Logarithm


x = [Link]([0, 1, 2, 3])
print([Link](x)) # [1.
Sh
2.718 7.389 20.09] — e^x
print([Link]([Link]([1, np.e, np.e**2]))) # [0. 1. 2.] — natural log
print(np.log10([Link]([1, 10, 100])))

# Trigonometric
# [0. 1. 2.] — log base 10

angles = [Link]([0, [Link]/6, [Link]/4, [Link]/2])


print([Link](angles).round(2)) # [0. 0.5 0.71 1. ]
h
print([Link](angles).round(2)) # [1. 0.87 0.71 0. ]

# Rounding
vals = [Link]([1.234, 5.678, 9.001])
ris

print([Link](vals, 2)) # [1.23 5.68 9. ]


print([Link](vals)) # [1. 5. 9.]
print([Link](vals)) # [2. 6. 10.]

4. Common Binary ufuncs


K

a = [Link]([2, 5, 8, 3])
b = [Link]([4, 1, 7, 9])

print([Link](a, b)) # [6 6 15 12]


print([Link](a, b)) # [-2 4 1 -6]
print([Link](a, b)) # [ 8 5 56 27]
print([Link](a, b)) # [0.5 5. 1.14 0.33]

# Element-wise maximum and minimum


print([Link](a, b)) # [4 5 8 9]
print([Link](a, b)) # [2 1 7 3]

NumPy | Pandas | Matplotlib — Page 13


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# Power
print([Link](a, 2)) # [ 4 25 64 9]

5. Aggregation / Reduction Functions

data = [Link]([[1, 2, 3],


[4, 5, 6],
[7, 8, 9]])

print([Link](data)) # 45 — total sum


print([Link](data, axis=0)) # [12 15 18] — column sums

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

NumPy | Pandas | Matplotlib — Page 14


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

Q5. Explain Array Input and Output in NumPy — how to save arrays to
files and load them back. Include [Link](), [Link](), [Link](), and
[Link]().

1. Overview of Array I/O

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.

2. [Link]() and [Link]() — Binary Format

import numpy as np

# Create and save a single array


Sh
arr = [Link]([[1.5, 2.3, 3.7], [4.1, 5.8, 6.2]])
[Link]('my_array.npy', arr)
# File 'my_array.npy' is created in binary format

# Load the array back


loaded = [Link]('my_array.npy')
print(loaded)
h
# [[1.5 2.3 3.7]
# [4.1 5.8 6.2]]
print([Link]) # float64 — dtype preserved exactly
ris

# Save multiple arrays together in a .npz file


a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
[Link]('multiple_arrays.npz', array_a=a, array_b=b)

# Load .npz file


data = [Link]('multiple_arrays.npz')
print(data['array_a']) # [1 2 3]
K

print(data['array_b']) # [4 5 6]

3. [Link]() — Save to Text/CSV

import numpy as np

stats = [Link]([[5.68, 3.03, 3.61, 1.22],


[6.90, 3.90, 5.90, 2.50],
[4.40, 2.30, 1.30, 0.10]])

NumPy | Pandas | Matplotlib — Page 15


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# Save as CSV with header comment


[Link]('iris_stats.csv',
stats,
delimiter=',',
fmt='%.2f',
header='sepal_len,sepal_wid,petal_len,petal_wid',
comments='')

# The file will contain:


# sepal_len,sepal_wid,petal_len,petal_wid
# 5.68,3.03,3.61,1.22
# 6.90,3.90,5.90,2.50
# 4.40,2.30,1.30,0.10

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

# Load a CSV file, skip the header row


iris = [Link]('[Link]',
skip_header=1,
delimiter=',',
Sh
dtype=float)

print([Link]) # e.g., (150, 5)


h
print(iris[:3]) # First 3 rows

# Load with column names (structured array)


data = [Link]('[Link]',
ris

delimiter=',',
names=True,
dtype=None,
encoding='utf-8')

Function Format Use Case dtype Preserved?


K

[Link]() .npy (binary) Save single array Yes — perfectly


efficiently
[Link]() .npz (binary) Save multiple arrays Yes — perfectly
in one file
[Link]() .txt / .csv Export for Excel, No — converted to
sharing, readability text
[Link]() .npy / .npz Load previously saved Yes
NumPy files

NumPy | Pandas | Matplotlib — Page 16


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

[Link]() .txt / .csv Load real-world Depends on dtype


datasets from files argument

ah
Sh
h
ris
K

NumPy | Pandas | Matplotlib — Page 17


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

SECTION A — PART II: PANDAS

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.

2. Where Pandas is Used

•​
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

•​ Business Intelligence: Sales analysis, inventory tracking, student performance evaluation.

3. Pandas vs NumPy — Key Differences

Aspect NumPy Pandas


K

Data Structure ndarray (homogeneous typed Series (1-D), DataFrame


array) (2-D), Panel (3-D)
Data Types Homogeneous — all elements Heterogeneous — each
same dtype column can have different
dtype
Index Integer-only, 0-based Custom labels: strings, dates,
integers, multi-level
Missing Values NaN only for floats; no built-in NaN/NaT with dedicated
handling functions: fillna(), dropna()

NumPy | Pandas | Matplotlib — Page 18


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

Best For Numeric array operations, Tabular data, time series,


linear algebra, image data database-like operations
File I/O Limited: .npy, .csv (genfromtxt) Rich: CSV, Excel, SQL, JSON,
Parquet, HTML, etc.
Column Labels No labels — positional only Named columns — makes
data intuitive and
self-documenting

4. Pandas Installation

ah
# Install Pandas
pip install pandas

# Import convention
import pandas as pd
import numpy as np

5. Pandas Series — Definition


Sh
A Pandas Series is a one-dimensional labelled array that can hold data of any type — integers, floats,
strings, Python objects, or even other data structures. Unlike a Python list, each element in a Series is
associated with an index label. By default, the index is a range of integers starting from 0.
Think of a Series as a single column in a spreadsheet — it has both values and row labels.
h
6. Creating Series from Scalar Values
ris

import pandas as pd

# Default integer index (0, 1, 2 ...)


s1 = [Link]([10, 20, 30, 40])
print(s1)
# 0 10
# 1 20
# 2 30
K

# 3 40
# dtype: int64

# Custom string index


s2 = [Link]([85, 92, 78, 95],
index=['Math', 'Science', 'English', 'History'])
print(s2)
# Math 85
# Science 92
# English 78
# History 95
# dtype: int64

NumPy | Pandas | Matplotlib — Page 19


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# Access by label
print(s2['Science']) # 92

# Access by position
print([Link][0]) # 85

7. Creating Series from NumPy Arrays

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

8. Creating Series from a Dictionary


h
capitals = {'India': 'New Delhi',
'UK': 'London',
'Japan': 'Tokyo',
'France': 'Paris'}
ris

s4 = [Link](capitals)
print(s4)
# India New Delhi
# UK London
# Japan Tokyo
# France Paris
# dtype: object
K

# Keys become the index, values become the data


print(s4['Japan']) # Tokyo

9. Series Operations and Methods

marks = [Link]([72, 85, 45, 91, 38],


index=['Alice', 'Bob', 'Charlie', 'David', 'Eve'])

NumPy | Pandas | Matplotlib — Page 20


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

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

NumPy | Pandas | Matplotlib — Page 21


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

Q7. Explain Pandas DataFrame in detail — creation methods, accessing


rows and columns, adding/dropping columns, and all essential
DataFrame operations.

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.

2. Creating a DataFrame from a Dictionary

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

print([Link]) # (4, 4) → 4 rows, 4 columns


print([Link])
# Name object
# Age int64
# Marks int64
# Grade object

print([Link]()) # ['Name', 'Age', 'Marks', 'Grade']


print([Link]()) # [0, 1, 2, 3]

3. Creating a DataFrame from a List of Dictionaries

NumPy | Pandas | Matplotlib — Page 22


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

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

# Access a single column (returns Series)


print(df['Marks'])
# 0
# 1
# 2
# 3
85
78
92
88
# Name: Marks, dtype: int64
Sh
# Access multiple columns (returns DataFrame)
print(df[['Name', 'Marks']])
# Name Marks
# 0 Alice 85
h
# 1 Bob 78
# 2 Charlie 92
# 3 Diana 88
ris

5. Accessing Rows — .loc[] and .iloc[]

# .loc[] — Label-based indexing


print([Link][0]) # First row by index label
print([Link][1:3]) # Rows with labels 1, 2, 3 (inclusive!)
K

print([Link][0, 'Name']) # Specific cell: row 0, column 'Name'

# .iloc[] — Integer position-based indexing


print([Link][0]) # First row (position 0)
print([Link][1:3]) # Rows at positions 1 and 2 (exclusive end)
print([Link][0, 2]) # Cell at row 0, column 2 → 85

# Accessing with condition (Boolean indexing)


print(df[df['Marks'] > 80])
# Name Age Marks Grade
# 0 Alice 20 85 A
# 2 Charlie 21 92 A+

NumPy | Pandas | Matplotlib — Page 23


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# 3 Diana 23 88 A

6. Adding and Dropping Columns/Rows

# Add a new column


df['Percentage'] = (df['Marks'] / 100) * 100
# Or compute from existing columns
df['Pass'] = df['Marks'] >= 80
print(df[['Name', 'Marks', 'Pass']])

# Drop a column

ah
df_dropped = [Link](columns=['Age'])
print(df_dropped.[Link]()) # ['Name', 'Marks', 'Grade', 'Percentage',
'Pass']

# Drop a row by index label


df_no_row2 = [Link](index=2)

# Drop with inplace=True (modifies original)

Sh
[Link](columns=['Percentage'], inplace=True)

7. Useful DataFrame Methods

Method Description Example


[Link](n) First n rows (default 5) [Link](3)
h
[Link](n) Last n rows (default 5) [Link](2)
[Link]() Index, columns, dtypes, [Link]()
memory usage
ris

[Link]() Summary statistics for numeric [Link]()


columns
[Link] Tuple (rows, cols) [Link] → (4, 4)
[Link] Column names (Index object) [Link]
[Link] Data type of each column [Link]
K

[Link]() Boolean mask of NaN [Link]().sum()


locations
df.value_counts() Count of unique values in a df['Grade'].value_counts()
Series
[Link]() Rename columns or index [Link](columns={'Age':'Ye
labels ars'})

NumPy | Pandas | Matplotlib — Page 24


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

Q8. Explain Index Objects, Reindexing, and Dropping Entries in Pandas


with detailed examples.

1. Index Objects in Pandas

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

s = [Link]([10, 20, 30], index=['a', 'b', 'c'])

# Accessing the Index object


idx = [Link]
print(idx) # Index(['a', 'b', 'c'], dtype='object')
print(type(idx))
print(idx[0])
#
#

# Checking membership
print('b' in idx)
print('z' in idx)

# DataFrame indices
# True
# False
'a'
Sh
<class '[Link]'>

df = [Link]({'A': [1, 2, 3], 'B': [4, 5, 6]})


print([Link]) # RangeIndex(start=0, stop=3, step=1)
print([Link]) # Index(['A', 'B'], dtype='object')
h
2. Reindexing
ris

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

# Reindex — adds 'May', drops 'Jan' is not dropped but reordered

NumPy | Pandas | Matplotlib — Page 25


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

new_idx = ['Feb', 'Mar', 'Apr', 'May', 'Jun']


s_reindexed = [Link](new_idx)
print(s_reindexed)
# Feb 200.0
# Mar 300.0
# Apr 400.0
# May NaN ← new label not in original → NaN
# Jun NaN

# Fill missing values during reindex


s_filled = [Link](new_idx, fill_value=0)
print(s_filled)
# Feb 200
# Mar 300

ah
# Apr 400
# May 0
# Jun 0

# Reindexing DataFrame columns


df = [Link]({'A': [1,2,3], 'B': [4,5,6]},
index=['x', 'y', 'z'])

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'])

3. Dropping Entries — drop()


h
The drop() method removes rows or columns from a Series or DataFrame. By default it does not modify
the original object — it returns a new object. To modify in-place, set inplace=True.
ris

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 single row by label


df1 = [Link](index=1) # Drop row with label 1 (Bob)
print(df1)

# Drop multiple rows


df2 = [Link](index=[0, 2]) # Drop Alice and Charlie

# Drop a column
df3 = [Link](columns='English')
print([Link]()) # ['Name', 'Maths', 'Science']

NumPy | Pandas | Matplotlib — Page 26


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# Drop multiple columns


df4 = [Link](columns=['Maths', 'English'])

# In-place drop (modifies original)


[Link](columns=['Science'], inplace=True)
print([Link]()) # ['Name', 'Maths', 'English']

📝 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

NumPy | Pandas | Matplotlib — Page 27


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

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]
})

# Select single column → Series


print(df['Salary'])

# Select multiple columns → DataFrame


print(df[['Name', 'Salary']])

# Select rows by condition


Sh
print(df[df['Salary'] > 70000])
# Name Dept Salary Age
# 1 Bob IT 80000 35
h
# 2 Charlie IT 75000 32
# 3 Diana Finance 90000 40
ris

# Multiple conditions (AND = &, OR = |)


print(df[(df['Dept'] == 'IT') & (df['Salary'] > 70000)])

# Select using .loc[rows, cols]


print([Link][1:3, ['Name', 'Salary']])
# Rows 1 to 3 (INCLUSIVE), columns Name and Salary

# Select using .iloc[row_pos, col_pos]


K

print([Link][0:3, 0:2])
# First 3 rows, first 2 columns (EXCLUSIVE end)

# .at[] and .iat[] — faster single-cell access


print([Link][2, 'Name']) # 'Charlie'
print([Link][2, 0]) # 'Charlie'

2. Data Alignment

NumPy | Pandas | Matplotlib — Page 28


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

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

s1 = [Link]({'A': 10, 'B': 20, 'C': 30})


s2 = [Link]({'B': 5, 'C': 15, 'D': 25})

# Automatic alignment: A in s1 not in s2 → NaN


# D in s2 not in s1 → NaN
result = s1 + s2
print(result)

ah
# A NaN
# B 25.0
# C 45.0
# D NaN
# dtype: float64

# Fill missing alignment values with 0


result2 = [Link](s2, fill_value=0)
print(result2)
# A
# B
# C
# D
10.0
25.0
45.0
25.0
Sh
# DataFrame alignment — aligns on BOTH rows and columns
df1 = [Link]({'X': [1, 2], 'Y': [3, 4]}, index=['a', 'b'])
df2 = [Link]({'Y': [10, 20], 'Z': [30, 40]}, index=['b', 'c'])
h
print(df1 + df2)
# X Y Z
# a NaN NaN NaN
# b NaN 14.0 NaN
ris

# c NaN NaN NaN

3. Sorting

import pandas as pd
K

df = [Link]({
'Name': ['Charlie', 'Alice', 'Eve', 'Bob', 'Diana'],
'Score': [92, 85, 78, 90, 88]
})

# Sort by column values


print(df.sort_values('Score'))
# Name Score
# 2 Eve 78
# 1 Alice 85
# 4 Diana 88
# 3 Bob 90

NumPy | Pandas | Matplotlib — Page 29


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# 0 Charlie 92

# Sort descending
print(df.sort_values('Score', ascending=False))

# Sort by multiple columns


df2 = [Link]({'Dept': ['IT', 'HR', 'IT', 'HR'],
'Salary': [80000, 55000, 75000, 60000]})
print(df2.sort_values(['Dept', 'Salary'], ascending=[True, False]))

# Sort by index
print(df.sort_index())
print(df.sort_index(ascending=False))

ah
4. Ranking

import pandas as pd

scores = [Link]([88, 92, 78, 95, 92])

# Default: average rank for ties


print([Link]())
# 0
# 1
# 2
# 3
3.0
4.5
1.0
5.0
Sh
← tied 92 → average of positions 4 and 5

# 4 4.5

# Rank with min method (lower rank wins the tie)


h
print([Link](method='min'))
# 0 3.0
# 1 4.0
ris

# 2 1.0
# 3 5.0
# 4 4.0

# Rank in descending order (1 = highest)


print([Link](ascending=False))
K

Method Parameter Behaviour for Tied Values


average (default) Average of the ranks assigned to the tied group
min All tied values get the minimum rank
max All tied values get the maximum rank
first Ranks assigned in order they appear in the
data
dense Like min, but rank always increases by 1 — no
gaps

NumPy | Pandas | Matplotlib — Page 30


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

ah
Sh
h
ris
K

NumPy | Pandas | Matplotlib — Page 31


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

Q10. Explain Summary Statistics in Pandas — describe(), mean(),


median(), mode(), std(), var(), and GroupBy with examples.

1. Summary Statistics Overview

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],
})

# Full statistical summary


print([Link]())
# Output:
#

# 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

2. Individual Statistical Methods

# Column-wise (default axis=0)


print([Link]()) # Max per column
print([Link]()) # Min per column
print([Link]()) # Sum per column
K

print([Link]()) # Arithmetic mean per column


print([Link]()) # Median per column
print([Link]()) # Standard deviation per column
print([Link]()) # Variance per column
print([Link]()) # Non-null count per column

# Mode (returns DataFrame since multiple modes possible)


print(df['Maths'].mode()) # Most frequent value

# Row-wise (axis=1) — max marks per student per test


print([Link](axis=1))

NumPy | Pandas | Matplotlib — Page 32


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# 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

# Zuhaire 21.666667 16.666667

# Multiple aggregation functions


print(grouped['Maths'].agg(['min', 'max', 'mean', 'sum']))
# Name min max mean sum
# Raman 14 22 19.000000 57
# Zuhaire 20 23 21.666667 65
K

# Count per group


print([Link]())
# Name
# Raman 3
# Zuhaire 3

NumPy | Pandas | Matplotlib — Page 33


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

Q11. Explain Missing Data in Pandas — detection, removal, and filling


strategies with detailed examples using isnull(), dropna(), and fillna().

1. What is Missing Data?

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.

2. Detecting Missing Values

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

# Detect missing values (True = missing)


print([Link]())
# Name Maths Science
# 0 False False False
# 1 False True False
# 2 True False False
# 3 False False True
K

# Count missing values per column


print([Link]().sum())
# Name 1
# Maths 1
# Science 1
# dtype: int64

# Percentage missing
print(([Link]().sum() / len(df)) * 100)
# Name 25.0
# Maths 25.0
# Science 25.0

NumPy | Pandas | Matplotlib — Page 34


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# notnull() → opposite of isnull()


print([Link]())

3. Removing Missing Values — dropna()

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]],
})

# Drop rows with ANY NaN


print([Link]())
# Name Maths Science
# 0 Alice 85.0 79.0

# Drop rows only where ALL values are NaN


Sh
print([Link](how='all'))
# (no change since no row is entirely NaN)
h
# Drop rows with NaN in specific columns only
print([Link](subset=['Maths']))
# Name Maths Science
# 0 Alice 85.0 79.0
ris

# 2 NaN 92.0 85.0


# 3 Diana 88.0 NaN

# Drop columns with any NaN


print([Link](axis=1))
# (all columns have NaN, so all are dropped)

# Threshold: keep rows with at least 2 non-NaN values


K

print([Link](thresh=2))

4. Filling Missing Values — fillna()

import pandas as pd
import numpy as np

df = [Link]({
'Maths': [85, [Link], 92, 88, [Link]],

NumPy | Pandas | Matplotlib — Page 35


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

'Science': [79, 90, [Link], [Link], 88],


})

# Fill all NaN with a constant value


print([Link](0))
# Maths Science
# 0 85.0 79.0
# 1 0.0 90.0
# 2 92.0 0.0
# 3 88.0 0.0
# 4 0.0 88.0

# Fill with column mean


df_filled = [Link]([Link]())

ah
print(df_filled)
# Maths NaN replaced with mean of 85,92,88 = 88.33

# Forward fill (pad): use value before the NaN


print([Link](method='pad'))
# Maths Science
# 0 85.0 79.0
# 1
# 2
85.0
92.0
90.0 ← filled from row 0
90.0 ← filled from row 1
Sh
# Backward fill (bfill): use value after the NaN
print([Link](method='bfill'))
# NaN filled with the next valid value

# Fill specific columns with different values


[Link]({'Maths': df['Maths'].mean(),
'Science': df['Science'].median()}, inplace=True)
h
Strategy Method When to Use
ris

Remove rows [Link]() When dataset is large and


missing rows are few
Fill with constant [Link](0) When 0 or -1 is a meaningful
substitute (e.g., absence)
Fill with mean [Link]([Link]()) Numeric columns with random
missing data (imputation)
K

Fill with median [Link]([Link]()) Numeric data with outliers


(median is robust)
Fill with mode [Link]([Link]()[0]) Categorical data (most
frequent value)
Forward fill [Link](method='pad') Time series — carry last
observation forward
Backward fill [Link](method='bfill') Time series — carry next
observation backward

NumPy | Pandas | Matplotlib — Page 36


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

Q12. Explain Index Hierarchy (MultiIndex) in Pandas with creation,


accessing data, and practical examples.

1. What is Index Hierarchy?

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

# Method 1: Using tuples


index = [Link].from_tuples([

])
('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

# Access using outer level


print(s['Raman'])
# Maths 85
# Science 90

# Access using both levels


print(s['Raman', 'Science']) # 90
K

3. Creating a MultiIndex DataFrame

import pandas as pd

# MultiIndex from tuples


idx = [Link].from_tuples([
('Raman', 'UT1'), ('Raman', 'UT2'), ('Raman', 'UT3'),
('Zuhaire', 'UT1'), ('Zuhaire', 'UT2'), ('Zuhaire', 'UT3'),

NumPy | Pandas | Matplotlib — Page 37


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

], 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

# Access all data for Raman


print([Link]['Raman'])
# Maths Science
# UT1 22 21
# UT2 21 20
# UT3 14 19

# Access specific test for Raman


print([Link][('Raman', 'UT2')])
# Maths
# Science
21
20
Sh
# Summary stats per student
print([Link](level='Name').mean())
# Maths Science
h
# Name
# Raman 19.00 20.000000
# Zuhaire 21.67 16.666667
ris

4. Resetting and Setting Index

# Convert MultiIndex back to regular DataFrame


df_reset = df.reset_index()
print(df_reset.head())
K

# Name Test Maths Science


# 0 Raman UT1 22 21

# Set a column as index


df_regular = [Link]({'City': ['Delhi','Mumbai','Chennai'],
'Population': [32, 20, 11]})
df_indexed = df_regular.set_index('City')
print(df_indexed)
# Population
# City
# Delhi 32
# Mumbai 20

NumPy | Pandas | Matplotlib — Page 38


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# Chennai 11

ah
Sh
h
ris
K

NumPy | Pandas | Matplotlib — Page 39


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

SECTION A — PART III: MATPLOTLIB

Q13. What is Matplotlib? Explain its architecture, installation, and the


components of a Matplotlib figure. Also describe the plot() function and
how to customise line plots.

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.

pip install matplotlib

# Standard import convention


h
import [Link] as plt
import numpy as np
ris

3. Components of a Matplotlib Figure

Understanding the anatomy of a Matplotlib figure is essential for customising plots:


•​ Figure: The overall window or canvas. A figure can contain one or more subplots (axes). Created
with [Link]().
•​ Axes: The actual plotting area within a figure where data is drawn. Not to be confused with 'axis'
K

(the x or y axis). A figure can contain multiple Axes objects.


•​ Axis: The number-line-like objects that define the data limits. Each Axes has an X-Axis and a
Y-Axis.
•​ Title: The chart heading set using [Link]() or ax.set_title().
•​ X-Label / Y-Label: Descriptive text for the horizontal and vertical axes, set using [Link]() and
[Link]().
•​ Ticks: The marks along the axis at specific values. Customised with [Link]() and [Link]().
•​ Legend: Identifies the plotted data series, added with [Link]().
•​ Grid: Background gridlines added with [Link](True).

NumPy | Pandas | Matplotlib — Page 40


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

4. Basic Line Plot

import [Link] as plt

# Data
date = ['25/12', '26/12', '27/12', '28/12']
temp = [8.5, 10.5, 6.8, 9.2]

# Create the plot


[Link](date, temp)

# Add labels and title

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.

5. Customising Line Plots

Matplotlib provides extensive customisation options through parameters passed to plot():


h
Parameter Description Example Values
color Line and marker colour 'red', 'green', '#FF5733', 'r', 'g'
ris

linestyle Style of the line 'solid', 'dashed', 'dotted',


'dashdot', 'None'
linewidth Width of the line in pixels 1 (thin), 2, 3 (thick)
marker Symbol at each data point 'o' (circle), '*' (star), 's'
(square), '^' (triangle)
K

markersize Size of the marker symbol 5, 8, 10, 15


label Text for the legend 'Temperature', 'Population'
alpha Transparency (0=invisible, 0.5, 0.8, 1.0
1=opaque)

import [Link] as plt


import numpy as np

height = [121.9, 124.5, 129.5, 134.6, 139.7, 147.3, 152.4, 157.5, 162.6]

NumPy | Pandas | Matplotlib — Page 41


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

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

[Link]('my_chart.png', dpi=300, bbox_inches='tight')


# Supported formats: .png, .jpg, .pdf, .svg, .eps
h
ris
K

NumPy | Pandas | Matplotlib — Page 42


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

Q14. Explain Bar Charts, Histograms, Scatter Plots, and Pie Charts in
Matplotlib with complete Python code and output explanation for each.

1. Bar Chart — [Link]()

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.

import [Link] as plt

ah
subjects = ['Maths', 'Science', 'English', 'History', 'Geography']
marks = [88, 75, 91, 69, 82]

# Vertical bar chart


[Link](subjects, marks,
color=['blue', 'green', 'red', 'orange', 'purple'],
edgecolor='black',
width=0.6)

[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

[Link]('Horizontal Bar Chart')


[Link]()

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

import [Link] as plt


import numpy as np

NumPy | Pandas | Matplotlib — Page 43


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# Generate student marks (normally distributed)


[Link](42)
marks = [Link](loc=65, scale=15, size=200)
marks = [Link](marks, 0, 100) # Clip to valid range

[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

scored between 50 and 80.

3. Scatter Plot — [Link]()


Sh
expected for normally distributed data. The red dashed vertical line marks the mean. Most students

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

# Study hours vs exam score


study_hours = [2, 3, 5, 6, 7, 8, 9, 10, 11, 12]
exam_scores = [40, 52, 63, 68, 72, 80, 85, 90, 87, 95]

[Link](study_hours, exam_scores,
color='darkred',
marker='o',
s=80, # marker size
K

alpha=0.8,
label='Students')

[Link]('Study Hours per Day')


[Link]('Exam Score (%)')
[Link]('Study Hours vs Exam Score')
[Link]()
[Link](True, alpha=0.4)
[Link]()

# Example with two groups (comparison)


group_A_x = [Link](50)

NumPy | Pandas | Matplotlib — Page 44


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

group_A_y = group_A_x * 1.5 + [Link](50) * 0.5


group_B_x = [Link](50) + 2
group_B_y = group_B_x * 0.8 + [Link](50) * 0.5

[Link](group_A_x, group_A_y, color='blue', label='Group A', alpha=0.6)


[Link](group_B_x, group_B_y, color='red', label='Group B', alpha=0.6)
[Link]()
[Link]('Two-Group Scatter Comparison')
[Link]()

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.

import [Link] as plt

departments
headcount
explode
=
=
=
[40, 25, 15, 10, 10]
Sh
['Engineering', 'Marketing', 'HR', 'Finance', 'Operations']

[0.05, 0, 0, 0, 0] # Slightly offset Engineering


colors = ['#3498DB', '#E74C3C', '#2ECC71', '#F39C12', '#9B59B6']

[Link](headcount,
h
labels=departments,
autopct='%1.1f%%', # Show percentage inside slices
startangle=90, # Start from top
explode=explode,
ris

colors=colors,
shadow=True)

[Link]('Employee Distribution by Department')


[Link]('equal') # Ensures circular pie (not oval)
[Link]()
K

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.

NumPy | Pandas | Matplotlib — Page 45


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

Q15. Explain Multiple Plots, Subplots, and the Pandas Plot Function with
examples showing how Pandas integrates with Matplotlib for data
visualisation.

1. Plotting Multiple Lines on the Same Chart

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

x = [Link](0, 2 * [Link], 100)

[Link](x, [Link](x), color='blue', label='sin(x)', linewidth=2)


[Link](x, [Link](x), color='red', label='cos(x)', linewidth=2)

linestyle='dashed')

[Link](-2, 2)

[Link]('y')
Sh
[Link](x, [Link](x), color='green', label='tan(x)', linewidth=1,

# Limit y-axis to avoid tan explosion


[Link]('x (radians)')

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

import [Link] as plt


import numpy as np
K

x = [Link](0, 10, 100)

# Figure with 2 rows and 2 columns = 4 subplots


[Link](figsize=(12, 8))

# Subplot 1 — Line
[Link](2, 2, 1)
[Link](x, [Link](x), 'b-')
[Link]('Line Plot: sin(x)')
[Link](True)

NumPy | Pandas | Matplotlib — Page 46


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

# 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')

plt.tight_layout() # Prevents overlap between subplots


[Link]()

3. Pandas Built-in Plot Function


Sh
Pandas DataFrames and Series have a built-in .plot() method that wraps Matplotlib internally. This
allows quick visualisation directly from a DataFrame without manually extracting columns and calling
Matplotlib functions.

import pandas as pd
h
import [Link] as plt

# Create a sample DataFrame


df = [Link]({
ris

'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],


'Sales': [150, 200, 180, 220, 270, 310],
'Expenses': [100, 140, 130, 160, 190, 220]
})
df.set_index('Month', inplace=True)

# Line plot (default kind)


[Link](title='Monthly Sales vs Expenses',
K

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

# Histogram from DataFrame

NumPy | Pandas | Matplotlib — Page 47


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

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

# Scatter plot using Pandas


data = [Link]({'Height': [160, 170, 155, 180, 165],
'Weight': [55, 70, 50, 80, 62]})
[Link](kind='scatter', x='Height', y='Weight',
title='Height vs Weight',
color='darkblue', s=80)
[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

NumPy | Pandas | Matplotlib — Page 48


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

QUICK REVISION SUMMARY

Library Full Name Primary Use Key Objects


NumPy Numerical Python Numerical ndarray
computation, array
operations, linear
algebra
Pandas PANel DAta Data manipulation, Series, DataFrame
tabular data, time
series, data cleaning

ah
Matplotlib Mathematical Plotting Data visualisation — Figure, Axes
Library charts, graphs, plots

Topic Key Functions/Methods Notes


NumPy Array Creation [Link](), [Link](), All from numpy module
[Link](), [Link](),

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

Vectorised, no loops needed


[Link](), [Link](),
[Link]()
NumPy I/O [Link](), [Link](), .npy = binary, .csv = text
h
[Link](), [Link]()
Pandas Series [Link](list/dict/array) 1-D labelled array
ris

Pandas DataFrame [Link](dict/list) 2-D tabular data structure


Selection .loc[] label-based, .iloc[] loc is inclusive at both ends
position-based
Missing Data isnull(), dropna(), fillna() NaN for numeric, None for
objects
GroupBy [Link]('col').agg() Split-Apply-Combine pattern
K

Sorting sort_values(), sort_index() Use ascending= parameter


Ranking df['col'].rank(method=) method: average, min, max,
dense
Line Plot [Link](x, y, color=, linestyle=, Default chart type
marker=)
Bar Chart [Link](x, height) Categorical comparisons
Histogram [Link](x, bins=) Distribution of continuous data
Scatter [Link](x, y, s=, c=) Relationships/correlations

NumPy | Pandas | Matplotlib — Page 49


Unit 5: Python for Data AnalysisUniversity Exam Question Bank

Pie [Link](x, labels=, autopct=) Parts of a whole


Subplots [Link](rows, cols, index) Multiple charts in one figure
Pandas Plot [Link](kind=, title=, figsize=) Quick plotting from DataFrame

✅ 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

NumPy | Pandas | Matplotlib — Page 50

You might also like