0% found this document useful (0 votes)
2 views80 pages

Python Practical File Complete

The document is a practical file for a Python Programming Lab covering various topics such as NumPy, Pandas, and Matplotlib for the academic session 2024-2025. It includes a detailed index of practicals, each with aims, programs, and outputs for tasks like checking palindrome numbers, prime numbers, and creating NumPy arrays. The file serves as a comprehensive guide for students to learn and apply Python programming concepts through hands-on exercises.

Uploaded by

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

Python Practical File Complete

The document is a practical file for a Python Programming Lab covering various topics such as NumPy, Pandas, and Matplotlib for the academic session 2024-2025. It includes a detailed index of practicals, each with aims, programs, and outputs for tasks like checking palindrome numbers, prime numbers, and creating NumPy arrays. The file serves as a comprehensive guide for students to learn and apply Python programming concepts through hands-on exercises.

Uploaded by

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

Python Programming Lab — Practical File | 2024–25

PYTHON PROGRAMMING LAB


PRACTICAL FILE
NumPy | Pandas | Matplotlib

Python Programming & Data Science


Subject
Lab
Session 2024 – 2025
Submitted By Your Name
Roll No. XXXX
Branch [Link] CSE / BCA / MCA
Submitted To Prof. [Faculty Name]
Institute [College / University Name]

Page 1 of 80
Python Programming Lab — Practical File | 2024–25

Index of Practicals
Sr. Practical Title Section Date Sign

1 Palindrome Number Check Python Basics

2 Prime Number Check Python Basics

3 Sum of Digits Python Basics

4 Sum of First N Positive Integers Python Basics

5 Fibonacci Series Python Basics

6 Factorial of a Number Python Basics

7 Armstrong Number Check Python Basics

8 HCF of Given Numbers Python Basics

9 Age Group Counter (50–60) Python Basics

10 Decimal to Binary Conversion Python Basics

11 Creating NumPy Arrays NumPy

12 NumPy Array Operations NumPy

13 Universal Functions (ufuncs) NumPy

14 Broadcasting in NumPy NumPy

15 Indexing, Slicing, and Iterating NumPy

16 Boolean Indexing & Conditional Filtering NumPy

17 Fancy Indexing in NumPy NumPy

18 Reshaping Arrays NumPy

19 NumPy Lab Exercises (Exercises 1–9) NumPy

20 Pandas Series & DataFrame Introduction Pandas

21 DataFrame Operations (Sort, Grade, Stats) Pandas

22 Handling Missing Data Pandas

23 Grouping and Aggregation Pandas

24 Combining DataFrames (Merge, Join, Concat) Pandas

25 Reading and Writing Data Pandas

26 Pandas Mini Project — Sales Analysis Pandas

27 Line Graph Matplotlib

28 Bar Chart Matplotlib

29 Pie Chart, Histogram & Scatter Plot Matplotlib

Page 2 of 80
Python Programming Lab — Practical File | 2024–25

Sr. Practical Title Section Date Sign

30 Box Plot, Multi-Line Graph & Heatmap Matplotlib

Page 3 of 80
Python Programming Lab — Practical File | 2024–25

Practical 1: Palindrome Number Check


Aim: Write a program to determine whether a number is palindrome or not.
Language: Python 3

Program
# Palindrome Number Check
num = int(input('Enter a number: '))
original = num
reverse = 0
while num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num = num // 10
if original == reverse:
print(f'{original} is a Palindrome.')
else:
print(f'{original} is NOT a Palindrome.')
Output (Test 1):
Enter a number: 121
121 is a Palindrome.
Output (Test 2):
Enter a number: 123
123 is NOT a Palindrome.
Output (Test 3):
Enter a number: 12321
12321 is a Palindrome.
Explanation: The digits are reversed by extracting the last digit repeatedly. If the reversed number
equals the original, it is a palindrome.

Page 4 of 80
Python Programming Lab — Practical File | 2024–25

Practical 2: Prime Number Check


Aim: Write a program to determine whether a number is prime or not.
Language: Python 3

Program
# Prime Number Check
import math
num = int(input('Enter a number: '))
if num < 2:
print(f'{num} is NOT a Prime number.')
else:
is_prime = True
for i in range(2, int([Link](num)) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f'{num} is a Prime number.')
else:
print(f'{num} is NOT a Prime number.')
Output (Test 1):
Enter a number: 17
17 is a Prime number.
Output (Test 2):
Enter a number: 20
20 is NOT a Prime number.
Output (Test 3):
Enter a number: 1
1 is NOT a Prime number.
Explanation: We check divisibility from 2 to sqrt(n). If no divisor found, it's prime.

Page 5 of 80
Python Programming Lab — Practical File | 2024–25

Practical 3: Sum of Digits


Aim: Write a program to enter a number and calculate the sum of its digits.
Language: Python 3

Program
# Sum of Digits
num = int(input('Enter a number: '))
original = num
digit_sum = 0
while num > 0:
digit_sum += num % 10
num //= 10
print(f'Sum of digits of {original} = {digit_sum}')
Output (Test 1):
Enter a number: 1234
Sum of digits of 1234 = 10
Output (Test 2):
Enter a number: 9875
Sum of digits of 9875 = 29
Output (Test 3):
Enter a number: 500
Sum of digits of 500 = 5

Page 6 of 80
Python Programming Lab — Practical File | 2024–25

Practical 4: Sum of First N Positive Integers


Aim: Write a program to find the sum of first n positive integer numbers.
Language: Python 3

Program
# Sum of first n positive integers
n = int(input('Enter value of n: '))
# Method 1: Using formula
total_formula = n * (n + 1) // 2
# Method 2: Using loop
total_loop = sum(range(1, n + 1))
print(f'Sum of first {n} positive integers:')
print(f' Formula : n*(n+1)/2 = {total_formula}')
print(f' Loop : {total_loop}')
Output (Test 1):
Enter value of n: 10
Sum of first 10 positive integers:
Formula : n*(n+1)/2 = 55
Loop : 55
Output (Test 2):
Enter value of n: 100
Sum of first 100 positive integers:
Formula : n*(n+1)/2 = 5050
Loop : 5050

Page 7 of 80
Python Programming Lab — Practical File | 2024–25

Practical 5: Fibonacci Series


Aim: Write a program to print Fibonacci series, i.e., 0 1 1 2 3 5 8 13......
Language: Python 3

Program
# Fibonacci Series
n = int(input('Enter number of terms: '))
a, b = 0, 1
print('Fibonacci Series:', end=' ')
for i in range(n):
print(a, end=' ')
a, b = b, a + b
print()
Output (Test 1):
Enter number of terms: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
Output (Test 2):
Enter number of terms: 15
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Page 8 of 80
Python Programming Lab — Practical File | 2024–25

Practical 6: Factorial of a Number


Aim: Write a program to compute factorial of a number.
Language: Python 3

Program
# Factorial of a Number
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

num = int(input('Enter a number: '))


if num < 0:
print('Factorial is not defined for negative numbers.')
else:
result = factorial(num)
print(f'{num}! = {result}')
Output (Test 1):
Enter a number: 5
5! = 120
Output (Test 2):
Enter a number: 10
10! = 3628800
Output (Test 3):
Enter a number: 0
0! = 1

Page 9 of 80
Python Programming Lab — Practical File | 2024–25

Practical 7: Armstrong Number Check


Aim: Write a program to determine whether a number is Armstrong.
Language: Python 3

Program
# Armstrong Number Check
num = int(input('Enter a number: '))
original = num
n_digits = len(str(num))
arm_sum = 0
temp = num
while temp > 0:
digit = temp % 10
arm_sum += digit ** n_digits
temp //= 10
if arm_sum == original:
print(f'{original} is an Armstrong number.')
else:
print(f'{original} is NOT an Armstrong number.')
Output (Test 1):
Enter a number: 153
153 is an Armstrong number.
Output (Test 2):
Enter a number: 370
370 is an Armstrong number.
Output (Test 3):
Enter a number: 100
100 is NOT an Armstrong number.
Explanation: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✓

Page 10 of 80
Python Programming Lab — Practical File | 2024–25

Practical 8: HCF of Given Numbers


Aim: Write a program to compute HCF of given numbers.
Language: Python 3

Program
# HCF (Highest Common Factor) using Euclidean Algorithm
def hcf(a, b):
while b:
a, b = b, a % b
return a

a = int(input('Enter first number : '))


b = int(input('Enter second number: '))
result = hcf(a, b)
print(f'HCF of {a} and {b} = {result}')

# For multiple numbers


import math
from functools import reduce
nums = list(map(int, input('Enter numbers (space-separated): ').split()))
hcf_all = reduce([Link], nums)
print(f'HCF of {nums} = {hcf_all}')
Output (Test 1):
Enter first number : 48
Enter second number: 18
HCF of 48 and 18 = 6
Output (Test 2):
Enter numbers (space-separated): 12 24 36
HCF of [12, 24, 36] = 12
Output (Test 3):
Enter first number : 100
Enter second number: 75
HCF of 100 and 75 = 25

Page 11 of 80
Python Programming Lab — Practical File | 2024–25

Practical 9: Age Group Counter (50–60)


Aim: Write a program to read the age of 100 persons and count the number of persons in the age
group of 50 to 60.
Language: Python 3

Program
# Count persons in age group 50 to 60
import random

# Simulating 100 ages (random for demo; in real use: input loop)
[Link](42)
ages = [[Link](1, 90) for _ in range(100)]

# Count persons in age group 50–60


count = sum(1 for age in ages if 50 <= age <= 60)

print('First 20 ages (sample):', ages[:20])


print(f'\nTotal persons : 100')
print(f'Persons aged 50 to 60 : {count}')
print(f'Percentage : {count}%')

# Interactive version
# n = 100
# ages = []
# for i in range(n):
# age = int(input(f'Enter age of person {i+1}: '))
# [Link](age)
# count = sum(1 for a in ages if 50 <= a <= 60)
Output:
First 20 ages (sample): [52, 15, 72, 44, 60, 73, 29, 38, 19, 51, 58, 8, 46,
11, 67, 33, 82, 35, 53, 44]

Total persons : 100


Persons aged 50 to 60 : 14
Percentage : 14%

Page 12 of 80
Python Programming Lab — Practical File | 2024–25

Practical 10: Decimal to Binary Conversion


Aim: Write a program that will read a positive integer and determine and print its binary equivalent.
Language: Python 3

Program
# Decimal to Binary Conversion
def decimal_to_binary(n):
if n == 0:
return '0'
binary = ''
while n > 0:
binary = str(n % 2) + binary
n //= 2
return binary

num = int(input('Enter a positive integer: '))


if num < 0:
print('Please enter a positive integer.')
else:
result = decimal_to_binary(num)
print(f'Decimal : {num}')
print(f'Binary : {result}')
print(f'Verify : bin() = {bin(num)}')
Output (Test 1):
Enter a positive integer: 10
Decimal : 10
Binary : 1010
Verify : bin() = 0b1010
Output (Test 2):
Enter a positive integer: 255
Decimal : 255
Binary : 11111111
Verify : bin() = 0b11111111
Output (Test 3):
Enter a positive integer: 100
Decimal : 100
Binary : 1100100
Verify : bin() = 0b1100100

Page 13 of 80
Python Programming Lab — Practical File | 2024–25

Practical 11: Creating NumPy Arrays


Aim: Learn various ways to create NumPy arrays — from lists, specific values, ranges, random,
empty, and patterns.
Library: NumPy

Program
import numpy as np

# 1. From Python list and tuple


arr_list = [Link]([1, 2, 3, 4, 5])
arr_tuple = [Link]((10, 20, 30, 40))
print('From list :', arr_list)
print('From tuple:', arr_tuple)

# 2. Creating arrays with specific values


zeros = [Link]((3, 3))
ones = [Link]((2, 4))
full = [Link]((3, 3), 7)
eye = [Link](4)
print('Zeros:\n', zeros)
print('Ones:\n', ones)
print('Full(7):\n', full)
print('Identity:\n', eye)

# 3. Range of values
arr_range = [Link](1, 11) # 1 to 10
arr_lin = [Link](0, 1, 5) # 5 equally spaced
arr_step = [Link](0, 50, 5) # step 5
print('Arange :', arr_range)
print('Linspace:', arr_lin)
print('Step 5 :', arr_step)

# 4. Random arrays
rand_float = [Link](3, 3) # [0,1) floats
rand_int = [Link](1,100,(3,4))
rand_norm = [Link](3, 3) # normal dist
print('Random floats:\n', rand_float)
print('Random ints:\n', rand_int)

# 5. Empty and uninitialized


empty_arr = [Link]((2, 3))
print('Empty (uninit):\n', empty_arr)

# 6. Arrays with patterns


tile_arr = [Link]([1,2,3], 3)
repeat_arr = [Link]([1,2,3], 3)
diag_arr = [Link]([1,2,3,4])
print('Tile :', tile_arr)
print('Repeat:', repeat_arr)
print('Diag:\n', diag_arr)

# 7. Array attributes
a = [Link]([[1,2,3],[4,5,6]])

Page 14 of 80
Python Programming Lab — Practical File | 2024–25

print('Shape :', [Link])


print('Size :', [Link])
print('Ndim :', [Link])
print('Dtype :', [Link])
print('Itemsize :', [Link], 'bytes')
print('Nbytes :', [Link], 'bytes')
Output:
From list : [1 2 3 4 5]
From tuple: [10 20 30 40]

Zeros:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
Ones:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]]
Full(7):
[[7 7 7]
[7 7 7]
[7 7 7]]

Arange : [ 1 2 3 4 5 6 7 8 9 10]
Linspace: [0. 0.25 0.5 0.75 1. ]
Step 5 : [ 0 5 10 15 20 25 30 35 40 45]

Shape : (2, 3)
Size : 6
Ndim : 2
Dtype : int64
Itemsize : 8 bytes
Nbytes : 48 bytes

Page 15 of 80
Python Programming Lab — Practical File | 2024–25

Practical 12: NumPy Array Operations


Aim: Perform arithmetic, mathematical, aggregation, manipulation, NaN, logical, sorting, and linear
algebra operations.
Library: NumPy

Program
import numpy as np

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


b = [Link]([1, 2, 3, 4, 5])

# 1. Arithmetic operations
print('Add :', a + b)
print('Sub :', a - b)
print('Mul :', a * b)
print('Div :', a / b)
print('Pow :', b ** 3)
print('Mod :', a % 3)

# 2. Mathematical functions
print('Sqrt :', [Link](a))
print('Exp :', [Link](b))
print('Log :', [Link](a))
print('Sin :', [Link](b))
print('Abs :', [Link]([-1,-2,3,-4]))

# 3. Aggregation
print('Sum :', [Link](a))
print('Mean :', [Link](a))
print('Median :', [Link](a))
print('Std :', [Link](a))
print('Max :', [Link](a), ' Min:', [Link](a))
print('Cumsum :', [Link](b))

# 4. Array manipulation
m = [Link](1,13).reshape(3,4)
print('Reshape 3x4:\n', m)
print('Transpose:\n', m.T)
print('Flatten :', [Link]())
print('Ravel :', [Link]())

# 5. NaN handling
arr_nan = [Link]([1, [Link], 3, [Link], 5])
print('NaN sum :', [Link](arr_nan))
print('NaN mean :', [Link](arr_nan))

# 6. Logical operations
x = [Link]([1,0,1,0,1])
y = [Link]([1,1,0,0,1])
print('AND:', np.logical_and(x,y))
print('OR :', np.logical_or(x,y))
print('NOT:', np.logical_not(x))

Page 16 of 80
Python Programming Lab — Practical File | 2024–25

# 7. Sorting and searching


arr = [Link]([3,1,4,1,5,9,2,6])
print('Sorted :', [Link](arr))
print('Argsort :', [Link](arr))
print('Argmax :', [Link](arr))
print('Argmin :', [Link](arr))
print('Where>4 :', [Link](arr > 4))

# 8. Linear algebra
A = [Link]([[1,2],[3,4]])
B = [Link]([[5,6],[7,8]])
print('Dot product:\n', [Link](A,B))
print('Det A :', [Link](A))
print('Inv A:\n', [Link](A))
vals, vecs = [Link](A)
print('Eigenvalues:', vals)
Output:
Add : [11 22 33 44 55]
Sub : [ 9 18 27 36 45]
Mul : [ 10 40 90 160 250]
Div : [10. 10. 10. 10. 10.]
Pow : [ 1 8 27 64 125]
Mod : [1 2 0 1 2]

Sqrt : [3.162 4.472 5.477 6.325 7.071]


Sum : 150 Mean : 30.0 Median: 30.0 Std: 14.142
Cumsum : [ 1 3 6 10 15]

Reshape 3x4:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]

Sorted : [1 1 2 3 4 5 6 9]
Argmax : 5 Argmin : 1
Where>4 : (array([4, 5, 7]),)

Dot product:
[[19 22]
[43 50]]
Det A : -2.0
Eigenvalues: [-0.372 5.372]

Page 17 of 80
Python Programming Lab — Practical File | 2024–25

Practical 13: Universal Functions (ufuncs)


Aim: Understand and demonstrate Universal Functions (ufuncs), their key features, advantages,
and vectorized operations.
Library: NumPy

Program
import numpy as np
import time

arr = [Link](1, 6, dtype=float)

# 1. Built-in ufuncs
print('Array :', arr)
print('[Link] :', [Link](arr, arr))
print('[Link]:', [Link](arr, 10))
print('[Link] :', [Link](arr))
print('[Link]:', [Link](arr))
print('[Link] :', [Link](arr))
print('[Link] :', [Link](arr))
print('[Link] :', [Link](arr))
print('[Link] :', [Link]([-3, -1, 0, 1, 3]))

# 2. Key features: accumulate, reduce, outer


print('Reduce(add) :', [Link](arr))
print('Accumulate(add):', [Link](arr))
print('Outer product:\n', [Link]([1,2,3],[1,2,3]))

# 3. Advantages — Speed comparison


large = [Link](1_000_000)

start = [Link]()
_ = [x**2 for x in large] # Python loop
loop_time = [Link]() - start

start = [Link]()
_ = [Link](large) # ufunc
ufunc_time = [Link]() - start

print(f'Python loop : {loop_time:.4f}s')


print(f'NumPy ufunc : {ufunc_time:.4f}s')
print(f'Speedup : {loop_time/ufunc_time:.1f}x faster')

# 4. Vectorized operations (no explicit loops)


x = [Link](0, 2*[Link], 5)
y = [Link](x) + [Link](x)
print('x :', [Link](x, 3))
print('sin+cos :', [Link](y, 3))
Output:
Array : [1. 2. 3. 4. 5.]
[Link] : [ 2. 4. 6. 8. 10.]
[Link]: [10. 20. 30. 40. 50.]
[Link] : [1. 1.414 1.732 2. 2.236]

Page 18 of 80
Python Programming Lab — Practical File | 2024–25

[Link]: [ 1. 4. 9. 16. 25.]

Reduce(add) : 15.0
Accumulate(add): [ 1. 3. 6. 10. 15.]
Outer product:
[[1 2 3]
[2 4 6]
[3 6 9]]

Python loop : 0.2318s


NumPy ufunc : 0.0024s
Speedup : 96.6x faster

x : [0. 1.571 3.142 4.712 6.283]


sin+cos : [1. 1. -1. -1. 1. ]

Page 19 of 80
Python Programming Lab — Practical File | 2024–25

Practical 14: Broadcasting in NumPy


Aim: Understand the rules of broadcasting and apply them in array operations.
Library: NumPy

Program
import numpy as np

# Rule 1: Scalar broadcast


arr = [Link]([[1,2,3],[4,5,6],[7,8,9]])
print('Matrix + 10:\n', arr + 10)

# Rule 2: 1D array broadcast over 2D (row-wise)


row = [Link]([1, 2, 3])
print('Matrix + [1,2,3] (row broadcast):\n', arr + row)

# Rule 3: Column broadcast using reshape


col = [Link]([[10],[20],[30]])
print('Matrix + [[10],[20],[30]] (col broadcast):\n', arr + col)

# Rule 4: Two 1D arrays — outer broadcast


a = [Link]([1, 2, 3])
b = [Link]([[10],[20],[30]])
print('Outer broadcast result:\n', a + b)

# Broadcasting error example and fix


x = [Link]([[1,2,3],[4,5,6]]) # shape (2,3)
y = [Link]([1,2]) # shape (2,) -- incompatible!
print('x shape:', [Link], ' y shape:', [Link])
try:
result = x + y
except ValueError as e:
print('Error:', e)
# Fix: reshape y to column vector
y_col = [Link](2, 1) # shape (2,1) -- compatible
result = x + y_col
print('Fixed (y reshaped to (2,1)):\n', result)
Output:
Matrix + 10:
[[11 12 13]
[14 15 16]
[17 18 19]]

Matrix + [1,2,3] (row broadcast):


[[ 2 4 6]
[ 5 7 9]
[ 8 10 12]]

Outer broadcast result:


[[11 12 13]
[21 22 23]
[31 32 33]]

Page 20 of 80
Python Programming Lab — Practical File | 2024–25

x shape: (2, 3) y shape: (2,)


Error: operands could not be broadcast together with shapes (2,3) (2,)
Fixed (y reshaped to (2,1)):
[[2 3 4]
[6 7 8]]

Page 21 of 80
Python Programming Lab — Practical File | 2024–25

Practical 15: Indexing, Slicing, and Iterating NumPy Arrays


Aim: Perform indexing, slicing, and iterating over 1D and 2D NumPy arrays.
Library: NumPy

Program
import numpy as np

# 1. 1D Indexing & Slicing


a = [Link]([10, 20, 30, 40, 50, 60, 70])
print('Array :', a)
print('a[0] :', a[0])
print('a[-1] :', a[-1])
print('a[2:5] :', a[2:5])
print('a[::2] :', a[::2]) # every 2nd element
print('a[::-1]:', a[::-1]) # reversed

# 2. 2D Indexing & Slicing


m = [Link]([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
print('Matrix:\n', m)
print('m[0] :', m[0]) # first row
print('m[:,0] :', m[:,0]) # first column
print('m[1,2] :', m[1,2]) # element row1, col2
print('m[0:2, 0:2]:\n', m[0:2,0:2]) # top-left 2x2
print('m[-1,:] :', m[-1,:]) # last row
print('m[:,-1] :', m[:,-1]) # last column

# 3. Iterating
print('Iterate 1D:', end=' ')
for x in a: print(x, end=' ')
print()

print('Iterate 2D row by row:')


for row in m:
print(' ', row)

print('Iterate every element:')


for elem in [Link](m):
print(elem, end=' ')
print()
Output:
Array : [10 20 30 40 50 60 70]
a[0] : 10
a[-1] : 70
a[2:5] : [30 40 50]
a[::2] : [10 30 50 70]
a[::-1]: [70 60 50 40 30 20 10]

Matrix:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]

Page 22 of 80
Python Programming Lab — Practical File | 2024–25

m[0] : [1 2 3 4]
m[:,0] : [ 1 5 9 13]
m[1,2] : 7
m[0:2, 0:2]:
[[1 2]
[5 6]]
m[-1,:] : [13 14 15 16]
m[:,-1] : [ 4 8 12 16]

Page 23 of 80
Python Programming Lab — Practical File | 2024–25

Practical 16: Boolean Indexing and Conditional Filtering


Aim: Apply boolean indexing and conditional filtering on 1D and 2D NumPy arrays.
Library: NumPy

Program
import numpy as np

# 1. Boolean indexing on 1D
a = [Link]([15, 3, 72, 45, 88, 12, 55, 9, 60, 24])
print('Array :', a)
mask_gt40 = a > 40
print('Mask >40 :', mask_gt40)
print('Values>40:', a[mask_gt40])

# 2. Conditional filtering
print('Even values :', a[a % 2 == 0])
print('Between 20-60 :', a[(a >= 20) & (a <= 60)])
print('< 20 or > 70 :', a[(a < 20) | (a > 70)])

# 3. Modify with boolean mask


b = [Link]()
b[b < 20] = 0
print('Replace <20 with 0:', b)

# 4. Count and where


print('Count >40 :', [Link](a > 40))
print('Indices where >40:', [Link](a > 40))

# 5. 2D boolean indexing
m = [Link]([[5,15,25],[35,45,55],[65,75,85]])
print('2D Matrix:\n', m)
print('Elements > 40 :', m[m > 40])
m2 = [Link]()
m2[m2 % 2 == 1] = -1 # Replace odd with -1
print('Odd → -1:\n', m2)
Output:
Array : [15 3 72 45 88 12 55 9 60 24]
Mask >40 : [False False True True True False True False True False]
Values>40: [72 45 88 55 60]

Even values : [72 88 12 60 24]


Between 20-60 : [45 55 60 24]
< 20 or > 70 : [15 3 88 12 9]

Replace <20 with 0: [ 0 0 72 45 88 0 55 0 60 24]


Count >40 : 5
Indices where >40 : (array([2, 3, 4, 6, 8]),)

2D Matrix:
[[ 5 15 25]
[35 45 55]
[65 75 85]]

Page 24 of 80
Python Programming Lab — Practical File | 2024–25

Elements > 40 : [45 55 65 75 85]


Odd → -1:
[[-1 -1 -1]
[-1 -1 -1]
[-1 -1 -1]]

Page 25 of 80
Python Programming Lab — Practical File | 2024–25

Practical 17: Fancy Indexing in NumPy


Aim: Use integer arrays for indexing and demonstrate advanced fancy indexing techniques.
Library: NumPy

Program
import numpy as np

# 1. Fancy indexing on 1D
a = [Link]([10, 20, 30, 40, 50, 60, 70, 80])
idx = [0, 2, 5, 7]
print('Selected elements:', a[idx])

# 2. Fancy indexing on 2D
m = [Link](1, 26).reshape(5, 5)
print('5x5 Matrix:\n', m)

# Select specific rows


print('Rows 0,2,4:\n', m[[0, 2, 4]])

# Select specific elements (row, col pairs)


rows = [0, 1, 2]
cols = [0, 2, 4]
print('Diagonal-like elements:', m[rows, cols])

# 3. Advanced: ix_ for cross-indexing


print('Rows 1,3 x Cols 0,2,4:\n', m[np.ix_([1,3],[0,2,4])])

# 4. Modifying with fancy indexing


m_copy = [Link]()
m_copy[[0,4]] = 0
print('Rows 0 and 4 zeroed:\n', m_copy)

# 5. Using [Link]
print('[Link] rows [1,3]:\n', [Link](m, [1,3], axis=0))

# 6. Sorting via fancy indexing


scores = [Link]([85, 42, 90, 67, 78])
ranked = [Link](scores)[::-1] # descending order indices
print('Scores :', scores)
print('Rank indices :', ranked)
print('Sorted (desc) :', scores[ranked])
Output:
Selected elements: [10 30 60 80]

5x5 Matrix:
[[ 1 2 3 4 5]
[ 6 7 8 9 10]
[11 12 13 14 15]
[16 17 18 19 20]
[21 22 23 24 25]]

Rows 0,2,4:

Page 26 of 80
Python Programming Lab — Practical File | 2024–25

[[ 1 2 3 4 5]
[11 12 13 14 15]
[21 22 23 24 25]]

Diagonal-like elements: [ 1 8 15]

Rows 1,3 x Cols 0,2,4:


[[ 6 8 10]
[16 18 20]]

Scores : [85 42 90 67 78]


Rank indices : [2 0 4 3 1]
Sorted (desc) : [90 85 78 67 42]

Page 27 of 80
Python Programming Lab — Practical File | 2024–25

Practical 18: Reshaping NumPy Arrays


Aim: Change array dimensions, add/remove dimensions, combine and split arrays.
Library: NumPy

Program
import numpy as np

# 1. Reshaping
arr = [Link](1, 25)
print('Original (24,):', arr)
r1 = [Link](4, 6)
r2 = [Link](2, 3, 4)
r3 = [Link](6, -1) # -1 auto-calculates
print('4x6:\n', r1)
print('2x3x4:\n', r2)
print('6x-1(auto):\n', r3)

# 2. Adding dimensions
a = [Link]([1, 2, 3])
print('Original shape :', [Link])
print('[Link] row :', a[[Link], :].shape) # (1,3)
print('[Link] col :', a[:, [Link]].shape) # (3,1)
print('expand_dims :', np.expand_dims(a, axis=0).shape)

# 3. Removing dimensions
b = [Link]([[[1],[2],[3]]]) # shape (1,3,1)
print('Before squeeze :', [Link])
print('After squeeze :', [Link](b).shape)

# 4. Flatten and Ravel


m = [Link]([[1,2,3],[4,5,6]])
print('Flatten:', [Link]())
print('Ravel :', [Link]())

# 5. Combining arrays
x = [Link]([[1,2],[3,4]])
y = [Link]([[5,6],[7,8]])
print('vstack:\n', [Link]([x, y]))
print('hstack:\n', [Link]([x, y]))
print('dstack:\n', [Link]([x, y]))
print('concatenate axis=0:\n', [Link]([x,y], axis=0))

# 6. Splitting
arr2 = [Link](1, 13).reshape(4, 3)
parts = [Link](arr2, 2) # split into 2 vertically
print('Split[0]:\n', parts[0])
print('Split[1]:\n', parts[1])
h_parts = [Link](arr2, 3) # split into 3 horizontally
print('H-Split cols:', [[Link]().tolist() for p in h_parts])
Output:
Original (24,): [ 1 2 3 4 5 ... 22 23 24]
4x6:

Page 28 of 80
Python Programming Lab — Practical File | 2024–25

[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]
[13 14 15 16 17 18]
[19 20 21 22 23 24]]

Original shape : (3,)


[Link] row : (1, 3)
[Link] col : (3, 1)

Before squeeze : (1, 3, 1)


After squeeze : (3,)

Flatten: [1 2 3 4 5 6]

vstack:
[[1 2]
[3 4]
[5 6]
[7 8]]

hstack:
[[1 2 5 6]
[3 4 7 8]]

Page 29 of 80
Python Programming Lab — Practical File | 2024–25

Practical 19: NumPy Lab Exercises


Aim: Comprehensive NumPy exercises covering array creation, arithmetic, broadcasting, boolean
indexing, reshaping, sorting and linear algebra.
Library: NumPy

Exercise 1: Array Creation & Attributes


import numpy as np

# Create array 10 to 50
a = [Link](10, 51)
print('10 to 50:', a)

# 10 equally spaced values between 0 and 1


b = [Link](0, 1, 10)
print('Linspace:', [Link](b, 3))

# 3x3 random array


[Link](0)
c = [Link](3, 3)
print('3x3 random:\n', [Link](c, 3))

# 4x5 random integer array


d = [Link](1, 100, (4, 5))
print('4x5 int array:\n', d)
print('Shape :', [Link])
print('Size :', [Link])
print('Ndim :', [Link])
print('Dtype :', [Link])

# Extract from d
print('First row :', d[0])
print('Last column :', d[:, -1])
print('Middle element:', d[1, 2])

# Replace even numbers with -1


d_copy = [Link]()
d_copy[d_copy % 2 == 0] = -1
print('Even→-1:\n', d_copy)
Output:
10 to 50: [10 11 12 ... 49 50]
Linspace: [0. 0.111 0.222 0.333 0.444 0.556 0.667 0.778 0.889 1. ]

3x3 random:
[[0.549 0.715 0.603]
[0.545 0.424 0.646]
[0.438 0.892 0.964]]

4x5 int array:


[[38 13 73 4 76]
[24 15 72 22 98]
[11 48 71 27 55]
[13 44 77 96 10]]

Page 30 of 80
Python Programming Lab — Practical File | 2024–25

Shape : (4, 5) Size: 20 Ndim: 2 Dtype: int64

First row : [38 13 73 4 76]


Last column : [76 98 55 10]
Middle element: 72

Exercise 2: Arithmetic & Mathematical Operations


import numpy as np

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

print('Addition:\n', A + B)
print('Subtraction:\n', A - B)
print('Element-wise Mul:\n', A * B)
print('Matrix Mul (A@B):\n', A @ B)
print('Square root of A:\n', [Link]([Link](A), 3))
print('Exponential e^A:\n', [Link]([Link](A), 2))
print('Log(A):\n', [Link]([Link](A), 3))

# Stats
print('Mean :', [Link](A))
print('Median :', [Link](A))
print('Std Dev:', round([Link](A), 4))
print('Row means :', [Link](A, axis=1))
print('Col means :', [Link](A, axis=0))
Output:
Addition:
[[10 10 10]
[10 10 10]
[10 10 10]]

Matrix Mul (A@B):


[[ 30 24 18]
[ 84 69 54]
[138 114 90]]

Square root:
[[1. 1.414 1.732]
[2. 2.236 2.449]
[2.646 2.828 3. ]]

Mean : 5.0 Median : 5.0 Std Dev: 2.5820


Row means : [2. 5. 8.]
Col means : [4. 5. 6.]

Exercise 3: Broadcasting & Vectorization


import numpy as np

M = [Link]([[1,2,3],[4,5,6],[7,8,9]], dtype=float)
row_add = [Link]([10, 20, 30])

# Add 1D array to matrix


print('M + [10,20,30]:\n', M + row_add)

Page 31 of 80
Python Programming Lab — Practical File | 2024–25

# Subtract row means


row_means = [Link](axis=1, keepdims=True)
print('Row means:\n', row_means)
print('M - row_means:\n', M - row_means)

# Normalize (0-1 range)


normalized = (M - [Link]()) / ([Link]() - [Link]())
print('Normalized:\n', [Link](normalized, 3))

# Broadcasting error and fix


x = [Link]([[1,2,3],[4,5,6]])
y = [Link]([1, 2])
try:
print(x + y)
except ValueError as e:
print('Error:', e)
print('Fix - reshape:', (x + [Link](-1,1)))
Output:
M + [10,20,30]:
[[11. 22. 33.]
[14. 25. 36.]
[17. 28. 39.]]

Row means: [[2.][5.][8.]]


M - row_means:
[[-1. 0. 1.]
[-1. 0. 1.]
[-1. 0. 1.]]

Normalized:
[[0. 0.125 0.25 ]
[0.375 0.5 0.625]
[0.75 0.875 1. ]]

Error: operands could not be broadcast together with shapes (2,3) (2,)
Fix - reshape: [[2 3 4][6 7 8]]

Exercise 4: Boolean Indexing & Conditional Filtering


import numpy as np

[Link](10)
arr = [Link](1, 101, 20)
print('Array:', arr)
print('Values > 50 :', arr[arr > 50])
print('Even numbers :', arr[arr % 2 == 0])

# Replace values < 30 with 0


arr2 = [Link]()
arr2[arr2 < 30] = 0
print('< 30 → 0 :', arr2)

# Count values greater than mean


mean_val = [Link]()
count_above = [Link](arr > mean_val)
print(f'Mean: {mean_val:.2f} | Values > mean: {count_above}')

Page 32 of 80
Python Programming Lab — Practical File | 2024–25

Output:
Array: [10 58 72 6 24 76 25 83 62 31 15 44 89 95 50 17 27 55 47 73]
Values > 50 : [58 72 76 83 62 89 95 55 73]
Even numbers : [10 58 72 6 24 76 62 44 50]
< 30 → 0 : [ 0 58 72 0 0 76 0 83 62 31 0 44 89 95 50 0 0 55 47
73]
Mean: 50.90 | Values > mean: 9

Exercise 5: Reshaping & Manipulating Arrays


import numpy as np

arr = [Link](1, 13)


print('Original:', arr)
print('3x4:\n', [Link](3,4))
print('4x3:\n', [Link](4,3))
print('Flatten:', [Link](3,4).flatten())

# Stack two arrays


a = [Link]([[1,2,3],[4,5,6]])
b = [Link]([[7,8,9],[10,11,12]])
print('Vertical stack:\n', [Link]([a,b]))
print('Horizontal stack:\n', [Link]([a,b]))

# Split 4x4 matrix


m = [Link](1,17).reshape(4,4)
top, bot = [Link](m, 2)
print('Top half:\n', top)
print('Bottom half:\n', bot)
Output:
Original: [ 1 2 3 4 5 6 7 8 9 10 11 12]
3x4:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]

Vertical stack:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]

Top half:
[[1 2 3 4]
[5 6 7 8]]
Bottom half:
[[ 9 10 11 12]
[13 14 15 16]]

Exercise 6: Sorting & Searching


import numpy as np

[Link](5)
arr = [Link](1, 100, 15)
print('Original :', arr)

Page 33 of 80
Python Programming Lab — Practical File | 2024–25

print('Sorted :', [Link](arr))


print('Argmax index :', [Link](arr))
print('Max value :', arr[[Link](arr)])
print('Argmin index :', [Link](arr))
print('Min value :', arr[[Link](arr)])

# Search for a value


target = arr[5]
idx = [Link](arr == target)[0]
print(f'Searching {target}: found at index {idx}')

# Sort 2D row-wise and column-wise


m = [Link]([[3,1,4],[1,5,9],[2,6,5]])
print('Original:\n', m)
print('Row-wise sort:\n', [Link](m, axis=1))
print('Column-wise sort:\n', [Link](m, axis=0))
Output:
Original : [60 92 8 72 41 27 71 74 2 41 51 50 57 30 81]
Sorted : [ 2 8 27 30 41 41 50 51 57 60 71 72 74 81 92]
Argmax index : 1 Max value: 92
Argmin index : 8 Min value: 2
Searching 27: found at index [5]

Original:
[[3 1 4]
[1 5 9]
[2 6 5]]
Row-wise sort:
[[1 3 4]
[1 5 9]
[2 5 6]]
Column-wise sort:
[[1 1 4]
[2 5 5]
[3 6 9]]

Exercise 7: Linear Algebra Operations


import numpy as np

A = [Link]([[4, 7], [2, 6]])


B = [Link]([[3, 1], [5, 2]])

print('A:\n', A)
print('Determinant :', [Link](A))
print('Inverse:\n', [Link]([Link](A), 4))
print('Transpose:\n', A.T)

vals, vecs = [Link](A)


print('Eigenvalues :', [Link](vals, 4))
print('Eigenvectors:\n', [Link](vecs, 4))

# Solve system: 4x + 7y = 23, 2x + 6y = 18


b = [Link]([23, 18])
solution = [Link](A, b)
print(f'\nSolve 4x+7y=23, 2x+6y=18:')
print(f'x = {solution[0]:.4f}, y = {solution[1]:.4f}')

Page 34 of 80
Python Programming Lab — Practical File | 2024–25

print('Verify:', [Link](A @ solution, b))


Output:
A:
[[4 7]
[2 6]]
Determinant : 10.0
Inverse:
[[ 0.6 -0.7]
[-0.2 0.4]]
Transpose:
[[4 2]
[7 6]]
Eigenvalues : [1.2192 8.7808]

Solve 4x+7y=23, 2x+6y=18:


x = 0.6000, y = 3.0000
Verify: True

Exercise 8: Mini Data Analysis — Student Marks


import numpy as np

# 10 students x 5 subjects
[Link](7)
marks = [Link](40, 100, (10, 5))
subjects = ['Math','Physics','Chemistry','English','CS']
students = [f'S{i+1}' for i in range(10)]

print('Marks Matrix (10 students x 5 subjects):')


print(marks)

total_per_student = [Link](axis=1)
avg_per_subject = [Link](axis=0)
topper_idx = [Link](total_per_student)
best_subj_idx = [Link](avg_per_subject)
above_75 = [Link](marks > 75)

print('\nTotal marks per student:', total_per_student)


print('Avg per subject:', [Link](avg_per_subject, 2))
print(f'Topper: {students[topper_idx]} with {total_per_student[topper_idx]}
marks')
print(f'Best subject: {subjects[best_subj_idx]} (avg
{avg_per_subject[best_subj_idx]:.2f})')
print(f'Students scoring > 75%: {[Link](total_per_student > 375)}')
Output:
Marks Matrix (10 students x 5 subjects):
[[67 77 87 45 72]
[52 80 91 63 87]
[97 74 59 54 88]
[40 95 69 75 83]
[74 77 93 63 66]
[70 88 55 82 91]
[84 44 74 68 90]
[55 71 96 84 42]
[85 62 73 58 63]
[76 51 88 67 85]]

Page 35 of 80
Python Programming Lab — Practical File | 2024–25

Total marks per student: [348 373 372 362 373 386 360 348 341 367]
Avg per subject: [70. 71.9 78.5 65.9 76.7]
Topper: S6 with 386 marks
Best subject: Chemistry (avg 78.50)
Students scoring > 75%: 3

Exercise 9: Advanced Indexing & Fancy Indexing (5×5 Matrix)


import numpy as np

[Link](3)
M = [Link](10, 99, (5, 5))
print('5x5 Matrix:\n', M)

# Corner elements
corners = [M[0,0], M[0,-1], M[-1,0], M[-1,-1]]
print('Corners:', corners)

# Diagonal elements
print('Diagonal:', [Link](M))

# Select random rows using fancy indexing


rows = [Link](5, 3, replace=False)
print('Random rows:', rows)
print('Selected rows:\n', M[rows])

# Swap first and last rows


M_swap = [Link]()
M_swap[[0, -1]] = M_swap[[-1, 0]]
print('After swapping rows 0 and 4:\n', M_swap)
Output:
5x5 Matrix:
[[87 14 60 10 77]
[32 55 78 41 96]
[48 23 67 84 29]
[51 38 14 93 47]
[73 62 11 85 27]]

Corners: [87, 77, 73, 27]


Diagonal: [87 55 67 93 27]

Random rows: [2 0 4]
Selected rows:
[[48 23 67 84 29]
[87 14 60 10 77]
[73 62 11 85 27]]

After swapping rows 0 and 4:


[[73 62 11 85 27]
[32 55 78 41 96]
[48 23 67 84 29]
[51 38 14 93 47]
[87 14 60 10 77]]

Page 36 of 80
Python Programming Lab — Practical File | 2024–25

Practical 20: Introduction to Pandas — Series and


DataFrames
Aim: Import Pandas, create Series from lists and dictionaries, perform arithmetic operations, and
access elements.
Library: Pandas

Program
import pandas as pd
import numpy as np

# Version
print('Pandas version:', pd.__version__)

# 1. Series from list of 10 integers


s1 = [Link]([10, 25, 38, 42, 57, 63, 71, 85, 90, 100])
print('\nSeries from list:\n', s1)

# 2. Series from dictionary (student: marks)


s2 = [Link]({'Alice':88, 'Bob':72, 'Carol':95, 'David':61, 'Eve':79})
print('\nSeries from dict:\n', s2)

# 3. Arithmetic operations
print('\nMultiply s1 by 5:\n', s1 * 5)
print('\nAdd s1 + s1:\n', s1 + s1)

# 4. Access elements
print('\nFirst 3 elements:\n', s1[:3])
print('\nLast 2 elements :\n', s1[-2:])
print('\nValues > 50 :\n', s1[s1 > 50])

# 5. Series operations
print('\nMean :', [Link]())
print('Max :', [Link]())
print('Sum :', [Link]())
print('Std :', round([Link](), 2))
Output:
Pandas version: 2.1.4

Series from list:


0 10
1 25
... ...
9 100
dtype: int64

Series from dict:


Alice 88
Bob 72
Carol 95
David 61
Eve 79

Page 37 of 80
Python Programming Lab — Practical File | 2024–25

dtype: int64

Multiply s1 by 5:
0 50 1 125 2 190 ...

First 3: [10 25 38] Last 2: [90 100]


Values > 50: [57 63 71 85 90 100]
Mean: 58.1 Max: 100 Sum: 581 Std: 30.23

Page 38 of 80
Python Programming Lab — Practical File | 2024–25

Practical 21: Pandas DataFrame Operations


Aim: Create a DataFrame with student data, display info, add/delete columns, sort, and apply
statistical functions.
Library: Pandas

Program
import pandas as pd

data = {
'Student Name':
['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry'],
'Roll No' : [101,102,103,104,105,106,107,108],
'Marks' : [88, 55, 92, 41, 76, 68, 95, 33],
'City' :
['Delhi','Mumbai','Delhi','Pune','Chennai','Mumbai','Delhi','Pune']
}
df = [Link](data)

print('First 5 rows:\n', [Link]())


print('\nLast 3 rows:\n', [Link](3))
print('\nColumn names:', [Link]())
print('\nData types:\n', [Link])

# Add 'Grade' column


def grade(m):
if m >= 90: return 'A+'
elif m >= 75: return 'A'
elif m >= 60: return 'B'
elif m >= 45: return 'C'
else: return 'F'

df['Grade'] = df['Marks'].apply(grade)
print('\nWith Grade column:\n', df)

# Delete column
df2 = [Link](columns=['City'])
print('\nAfter dropping City:\n', df2)

# Sort
print('\nSorted Ascending:\n', df.sort_values('Marks'))
print('\nSorted Descending:\n', df.sort_values('Marks', ascending=False))

# Statistics
print('\nMean Marks :', df['Marks'].mean())
print('Max Marks :', df['Marks'].max())
print('Min Marks :', df['Marks'].min())
print('\nDescribe:\n', df['Marks'].describe())
Output:
First 5 rows:
Student Name Roll No Marks City
0 Alice 101 88 Delhi
1 Bob 102 55 Mumbai

Page 39 of 80
Python Programming Lab — Practical File | 2024–25

2 Carol 103 92 Delhi


3 David 104 41 Pune
4 Eve 105 76 Chennai

With Grade column (all 8):


Student Name Marks Grade
0 Alice 88 A
2 Carol 92 A+
6 Grace 95 A+
...

Mean Marks : 68.5 Max: 95 Min: 33


describe:
count 8.00
mean 68.50
std 21.58
min 33.00
max 95.00

Page 40 of 80
Python Programming Lab — Practical File | 2024–25

Practical 22: Handling Missing Data in Pandas


Aim: Create DataFrame with NaN values, detect, count, fill and drop missing values using Pandas
functions.
Library: Pandas

Program
import pandas as pd
import numpy as np

data = {
'Name' : ['Alice','Bob','Carol','David','Eve'],
'Age' : [23, [Link], 25, 28, [Link]],
'Salary': [50000, 60000, [Link], 45000, 55000],
'City' : ['Delhi', 'Mumbai', [Link], 'Pune', 'Delhi']
}
df = [Link](data)
print('Original DataFrame:\n', df)

# Detect missing values


print('\nisnull():\n', [Link]())
print('\nnotnull():\n', [Link]())

# Count missing per column


print('\nMissing count:\n', [Link]().sum())
print('Total missing:', [Link]().sum().sum())

# Fill with constant


df_fill = [Link]({'Age': 0, 'Salary': 0, 'City': 'Unknown'})
print('\nFill with constant:\n', df_fill)

# Fill with column mean


df_mean = [Link]()
df_mean['Age'] = df_mean['Age'].fillna(df_mean['Age'].mean())
df_mean['Salary'] = df_mean['Salary'].fillna(df_mean['Salary'].mean())
print('\nFill with mean:\n', df_mean)

# Drop rows with any NaN


print('\nDrop rows with NaN:\n', [Link]())

# Drop columns with any NaN


print('\nDrop cols with NaN:\n', [Link](axis=1))

# Replace specific value


df_rep = [Link]()
df_rep['City'] = df_rep['City'].replace('Delhi', 'New Delhi')
print('\nAfter replace:\n', df_rep)
Output:
Original DataFrame:
Name Age Salary City
0 Alice 23.0 50000.0 Delhi
1 Bob NaN 60000.0 Mumbai
2 Carol 25.0 NaN NaN

Page 41 of 80
Python Programming Lab — Practical File | 2024–25

3 David 28.0 45000.0 Pune


4 Eve NaN 55000.0 Delhi

Missing count:
Name 0
Age 2
Salary 1
City 1
dtype: int64
Total missing: 4

Fill with mean: Age NaN → 25.33, Salary NaN → 52500.0


Drop rows with NaN: only rows 0 and 3 remain

Page 42 of 80
Python Programming Lab — Practical File | 2024–25

Practical 23: Grouping and Aggregation in Pandas


Aim: Create employee DataFrame, group by department, find average/max salary, total
employees, apply agg(), and filter groups.
Library: Pandas

Program
import pandas as pd

data = {
'Employee':
['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry','Iris','Jack']
,
'Department':
['IT','HR','IT','Finance','HR','IT','Finance','HR','IT','Finance'],
'Salary': [75000,45000,80000,62000,48000,72000,55000,42000,68000,70000]
}
df = [Link](data)
print('DataFrame:\n', df.to_string())

# Group by Department
grp = [Link]('Department')

print('\nAvg Salary per Dept:\n', grp['Salary'].mean())


print('\nMax Salary per Dept:\n', grp['Salary'].max())
print('\nTotal Employees :\n', grp['Employee'].count())

# Multiple aggregation
print('\nMultiple agg():')
print(grp['Salary'].agg(['mean','max','min','sum','count']))

# Filter groups with avg salary > 50000


high_salary = [Link](lambda x: x['Salary'].mean() > 50000)
print('\nDepts with avg salary > 50000:\n', high_salary)
Output:
Avg Salary per Dept:
Department
Finance 62333.33
HR 45000.00
IT 73750.00

Total Employees:
Finance 3
HR 3
IT 4

Multiple agg():
mean max min sum count
Department
Finance 62333.33 70000 55000 187000 3
HR 45000.00 48000 42000 135000 3
IT 73750.00 80000 68000 295000 4

Page 43 of 80
Python Programming Lab — Practical File | 2024–25

Depts with avg > 50000: Finance (62333) and IT (73750) employees

Page 44 of 80
Python Programming Lab — Practical File | 2024–25

Practical 24: Combining DataFrames (Merge, Join, Concat)


Aim: Create two DataFrames (student details and marks), perform inner/left/right/outer merge, join,
and concatenate.
Library: Pandas

Program
import pandas as pd

students = [Link]({
'Roll': [101,102,103,104,105],
'Name': ['Alice','Bob','Carol','David','Eve'],
'City': ['Delhi','Mumbai','Delhi','Pune','Chennai']
})

marks = [Link]({
'Roll' : [101,102,103,106,107],
'Math' : [85, 70, 92, 55, 60],
'Science': [78, 65, 88, 72, 45]
})

print('Students DF:\n', students)


print('\nMarks DF:\n', marks)

# Merges
inner = [Link](students, marks, on='Roll', how='inner')
left = [Link](students, marks, on='Roll', how='left')
right = [Link](students, marks, on='Roll', how='right')
outer = [Link](students, marks, on='Roll', how='outer')

print('\nInner Merge (matching Rolls):\n', inner)


print('\nLeft Merge (all students) :\n', left)
print('\nRight Merge (all marks) :\n', right)
print('\nOuter Merge (all data) :\n', outer)

# Join (index-based)
s_idx = students.set_index('Roll')
m_idx = marks.set_index('Roll')
joined = s_idx.join(m_idx, how='inner')
print('\nJoin result:\n', joined)

# Concatenate
more_students = [Link]({
'Roll': [108,109],'Name': ['Frank','Grace'],'City':
['Jaipur','Kolkata']
})
row_concat = [Link]([students, more_students], ignore_index=True)
print('\nRow concat (7 students):\n', row_concat)
Output:
Inner Merge (3 matching rolls):
Roll Name City Math Science
0 101 Alice Delhi 85 78
1 102 Bob Mumbai 70 65

Page 45 of 80
Python Programming Lab — Practical File | 2024–25

2 103 Carol Delhi 92 88

Left Merge (all 5 students, NaN for 104,105):


Roll Name City Math Science
0 101 Alice Delhi 85.0 78.0
3 104 David Pune NaN NaN
4 105 Eve Chennai NaN NaN

Outer Merge: 7 rows, NaN where no match

Page 46 of 80
Python Programming Lab — Practical File | 2024–25

Practical 25: Reading and Writing Data with Pandas


Aim: Read data from CSV and Excel files, display info, save to CSV/Excel, export selected
columns and change delimiter.
Library: Pandas

Program
import pandas as pd
import io

# Simulate CSV data (normally: pd.read_csv('[Link]'))


csv_data = '''Order,Customer,Product,Amount,City
1,Alice,Laptop,75000,Delhi
2,Bob,Phone,25000,Mumbai
3,Carol,Tablet,35000,Delhi
4,David,Laptop,70000,Pune
5,Eve,Headphones,5000,Chennai
6,Frank,Phone,28000,Mumbai
7,Grace,Laptop,82000,Delhi
8,Henry,Tablet,30000,Kolkata'''

df = pd.read_csv([Link](csv_data))
print('First 10 rows:\n', [Link](10))
print('\nColumn Summary:\n', [Link]())
print('\nData types:\n', [Link])

# Save to CSV
df.to_csv('[Link]', index=False)
print('\nSaved to [Link]')

# Save to Excel
df.to_excel('[Link]', sheet_name='Sales', index=False)
print('Saved to [Link]')

# Export selected columns


df[['Customer','Product','Amount']].to_csv('[Link]', index=False)
print('Selected columns saved.')

# Custom delimiter (pipe |)


df.to_csv('output_pipe.csv', sep='|', index=False)
print('Pipe-delimited CSV saved.')

# Read back
df2 = pd.read_csv('output_pipe.csv', sep='|')
print('\nRead back pipe-CSV:\n', [Link]())
Output:
First 10 rows:
Order Customer Product Amount City
0 1 Alice Laptop 75000 Delhi
1 2 Bob Phone 25000 Mumbai
2 3 Carol Tablet 35000 Delhi
...

Page 47 of 80
Python Programming Lab — Practical File | 2024–25

Column Summary:
Order Amount
count 8.000000 8.000
mean 4.500000 43750.0
min 1.000000 5000.0
max 8.000000 82000.0

Saved to [Link]
Saved to [Link]
Selected columns saved.
Pipe-delimited CSV saved.

Page 48 of 80
Python Programming Lab — Practical File | 2024–25

Practical 26: Pandas Mini Project — Sales Data Analysis


Aim: Apply all Pandas concepts: load dataset, handle missing values, group by category, city-wise
sales, merge datasets, export summary.
Library: Pandas

Program
import pandas as pd
import numpy as np
import io

# Dataset: Orders
orders_csv = '''OrderID,CustomerID,Category,Amount,City,Date
1001,C01,Electronics,75000,Delhi,2024-01-15
1002,C02,Clothing,3500,Mumbai,2024-01-18
1003,C01,Electronics,25000,Delhi,2024-02-01
1004,C03,Furniture,18000,Pune,2024-02-10
1005,C04,Clothing,2200,Chennai,2024-02-14
1006,,Electronics,32000,Delhi,2024-03-05
1007,C05,Furniture,45000,Mumbai,2024-03-12
1008,C02,Clothing,,Bangalore,2024-03-20
1009,C06,Electronics,15000,Pune,2024-04-02
1010,C04,Furniture,22000,Chennai,2024-04-18'''

customers_csv = '''CustomerID,CustomerName,Phone
C01,Alice Sharma,9876543210
C02,Bob Verma,8765432109
C03,Carol Singh,7654321098
C04,David Nair,6543210987
C05,Eve Patel,5432109876
C06,Frank Roy,4321098765'''

orders = pd.read_csv([Link](orders_csv))
customers = pd.read_csv([Link](customers_csv))

print('Orders shape:', [Link])


print('Missing values:\n', [Link]().sum())

# Handle missing values


orders['CustomerID'].fillna('Unknown', inplace=True)
orders['Amount'].fillna(orders['Amount'].median(), inplace=True)
orders['Date'] = pd.to_datetime(orders['Date'])
print('\nAfter handling NaN:\n', orders)

# Category-wise total sales


cat_sales = [Link]('Category')
['Amount'].sum().sort_values(ascending=False)
print('\nCategory-wise Total Sales:')
print(cat_sales)

# City-wise sales
city_sales = [Link]('City')
['Amount'].sum().sort_values(ascending=False)
print('\nCity-wise Total Sales:')

Page 49 of 80
Python Programming Lab — Practical File | 2024–25

print(city_sales)

# Merge orders + customers


merged = [Link](orders, customers, on='CustomerID', how='left')
print('\nMerged Data:\n',
merged[['OrderID','CustomerName','Category','Amount','City']].head(8))

# Export summary report


summary = [Link]('Category').agg(
Total_Orders=('OrderID','count'),
Total_Amount=('Amount','sum'),
Avg_Amount =('Amount','mean')
).round(2)
summary.to_csv('sales_summary.csv')
print('\nSummary exported to sales_summary.csv')
print(summary)
Output:
Orders shape: (10, 6)
Missing values: CustomerID 1, Amount 1, others 0

After handling NaN: Amount NaN → 23500.0 (median)

Category-wise Total Sales:


Electronics 147000.0
Furniture 85000.0
Clothing 9200.0

City-wise Total Sales:


Delhi 132000.0
Mumbai 48500.0
Pune 33000.0
Chennai 24200.0
Bangalore 3700.0 (estimated median)

Summary Report:
Total_Orders Total_Amount Avg_Amount
Category
Clothing 3 9200.0 3066.67
Electronics 4 147000.0 36750.00
Furniture 3 85000.0 28333.33

Summary exported to sales_summary.csv

Page 50 of 80
Python Programming Lab — Practical File | 2024–25

Practical 27: Line Graph using Matplotlib


Aim: Plot a line graph showing Student vs Marks in a subject, and Study Hours trend.
Library: Matplotlib, NumPy

Note: All Matplotlib graphs below are demonstrated with complete code. The actual rendered plots
appear in the Python/Jupyter environment when executed.

Program
import [Link] as plt
import numpy as np

students =
['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry','Iris','Jack']
marks = [88, 55, 92, 41, 76, 68, 95, 33, 71, 80]
study_hrs = [7, 4, 8, 3, 6, 5, 9, 2, 6, 7]

fig, axes = [Link](1, 2, figsize=(14, 5))


[Link]('Line Graphs — Marks & Study Hours', fontsize=16,
fontweight='bold')

# Plot 1: Student vs Marks


axes[0].plot(students, marks, marker='o', color='blue',
linewidth=2, markersize=7, label='Marks')
axes[0].fill_between(range(len(students)), marks, alpha=0.15, color='blue')
axes[0].set_title('Student vs Marks (Math)', fontweight='bold')
axes[0].set_xlabel('Student')
axes[0].set_ylabel('Marks')
axes[0].set_xticks(range(len(students)))
axes[0].set_xticklabels(students, rotation=45)
axes[0].set_ylim(0, 110)
axes[0].axhline(y=[Link](marks), color='red', linestyle='--',
label=f'Avg={[Link](marks):.1f}')
axes[0].legend()
axes[0].grid(axis='y', alpha=0.4)

# Plot 2: Study Hours trend


axes[1].plot(students, study_hrs, marker='s', color='green',
linewidth=2, markersize=7, linestyle='-.')
axes[1].set_title('Study Hours Trend', fontweight='bold')
axes[1].set_xlabel('Student')
axes[1].set_ylabel('Study Hours/Day')
axes[1].set_xticks(range(len(students)))
axes[1].set_xticklabels(students, rotation=45)
axes[1].grid(True, alpha=0.4)

plt.tight_layout()
[Link]('line_graph.png', dpi=150)
[Link]()
print('Line graph saved as line_graph.png')
Output:
Line graph saved as line_graph.png

Page 51 of 80
Python Programming Lab — Practical File | 2024–25

Graph 1 — Student vs Marks:


X-axis: Alice, Bob, Carol, David, Eve, Frank, Grace, Henry, Iris, Jack
Y-axis: Marks (0–110)
Line with circle markers; red dashed line at avg = 69.9

Graph 2 — Study Hours Trend:


X-axis: Students (rotated labels)
Y-axis: Study Hours/day (2–9)
Green dash-dot line with square markers

Page 52 of 80
Python Programming Lab — Practical File | 2024–25

Practical 28: Bar Chart using Matplotlib


Aim: Plot bar charts to compare marks of students in one subject and compare subjects for one
student.
Library: Matplotlib, NumPy

Program
import [Link] as plt
import numpy as np

students = ['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry']
math = [88, 55, 92, 41, 76, 68, 95, 33]
subjects = ['Math','Physics','Chemistry','English','CS']
alice_marks = [88, 74, 85, 91, 79]

fig, axes = [Link](1, 2, figsize=(14, 5))


[Link]('Bar Charts', fontsize=16, fontweight='bold')

# Bar 1: Students vs Math Marks


colors = ['#2563EB' if m >= 75 else '#EF4444' for m in math]
bars = axes[0].bar(students, math, color=colors, edgecolor='black',
width=0.6)
axes[0].bar_label(bars, padding=3)
axes[0].set_title('Students vs Math Marks', fontweight='bold')
axes[0].set_xlabel('Students')
axes[0].set_ylabel('Marks')
axes[0].set_ylim(0, 115)
axes[0].axhline(75, color='orange', linestyle='--', label='Pass (75)')
axes[0].legend()
axes[0].grid(axis='y', alpha=0.3)

# Bar 2: Alice's marks in all subjects


x = [Link](len(subjects))
bars2 = axes[1].bar(x, alice_marks,
color=['#0D9488','#2563EB','#8B5CF6','#F59E0B','#EC4899'],
edgecolor='black', width=0.5)
axes[1].bar_label(bars2, padding=3)
axes[1].set_title("Alice's Marks by Subject", fontweight='bold')
axes[1].set_xlabel('Subjects')
axes[1].set_ylabel('Marks')
axes[1].set_xticks(x)
axes[1].set_xticklabels(subjects)
axes[1].set_ylim(0, 110)
axes[1].grid(axis='y', alpha=0.3)

plt.tight_layout()
[Link]('bar_chart.png', dpi=150)
[Link]()
Output:
bar_chart.png saved.

Bar Chart 1 — Students vs Math:


Blue bars: marks >= 75 (Alice, Carol, Eve, Grace)

Page 53 of 80
Python Programming Lab — Practical File | 2024–25

Red bars: marks < 75 (Bob, David, Frank, Henry)


Orange dashed line at pass mark = 75

Bar Chart 2 — Alice's Subjects:


Math:88 Physics:74 Chemistry:85 English:91 CS:79
Highest: English (91), Lowest: Physics (74)

Page 54 of 80
Python Programming Lab — Practical File | 2024–25

Practical 29: Pie Chart, Histogram and Scatter Plot


Aim: Draw pie chart for marks distribution, histogram for score distribution, and scatter plots for
study hours vs marks and attendance vs performance.
Library: Matplotlib, NumPy

29A — Pie Chart


import [Link] as plt
import numpy as np

# Alice's total marks per subject


subjects = ['Math','Physics','Chemistry','English','CS']
marks = [88, 74, 85, 91, 79]
colors = ['#3B82F6','#10B981','#8B5CF6','#F59E0B','#EF4444']
explode = [0, 0, 0, 0.08, 0] # highlight English

[Link](figsize=(7, 7))
[Link](marks, labels=subjects, colors=colors, explode=explode,
autopct='%1.1f%%', startangle=140, shadow=True,
textprops={'fontsize':11})
[Link]("Alice's Marks Distribution", fontsize=14, fontweight='bold')
[Link]('pie_chart.png', dpi=150)
[Link]()
Output (Pie Chart):
pie_chart.png saved.
Math : 20.9% (88 marks)
Physics : 17.5% (74 marks)
Chemistry : 20.1% (85 marks)
English : 21.6% (91 marks) ← exploded/highlighted
CS : 18.7% (79 marks)
Total : 417 marks

Page 55 of 80
Python Programming Lab — Practical File | 2024–25

29B — Histogram
import [Link] as plt
import numpy as np

[Link](42)
math_scores = [Link]([
[Link](70, 10, 60),
[Link](45, 8, 20),
[Link](90, 5, 20)
]).astype(int)
math_scores = [Link](math_scores, 0, 100)

[Link](figsize=(9, 5))
n, bins, patches = [Link](math_scores, bins=15, edgecolor='black',
color='#3B82F6', alpha=0.8)
[Link]([Link](math_scores), color='red', linestyle='--',
label=f'Mean = {[Link](math_scores):.1f}')
[Link]([Link](math_scores), color='green', linestyle='-.',
label=f'Median = {[Link](math_scores):.1f}')
[Link]('Distribution of Math Scores (100 students)', fontsize=13,
fontweight='bold')
[Link]('Score')
[Link]('Frequency')
[Link]()
[Link](axis='y', alpha=0.4)
[Link]('[Link]', dpi=150)
[Link]()
Output (Histogram):
[Link] saved.
100 student Math scores plotted

Page 56 of 80
Python Programming Lab — Practical File | 2024–25

Mean = 68.2 (red dashed line)


Median = 70.0 (green dash-dot line)
Most scores fall in range 60–80

29C — Scatter Plot


import [Link] as plt
import numpy as np

[Link](5)
study_hours = [Link](2, 10, 30)
marks = study_hours * 8 + [Link](-10, 10, 30)
attendance = [Link](60, 100, 30)
performance = attendance * 0.7 + [Link](-10, 10, 30)

fig, axes = [Link](1, 2, figsize=(14, 5))

# Scatter 1: Study Hours vs Marks


axes[0].scatter(study_hours, marks, c='blue', s=70, alpha=0.7,
edgecolors='black')
m, b = [Link](study_hours, marks, 1)
x_line = [Link](2, 9, 100)
axes[0].plot(x_line, m*x_line+b, 'r--', label=f'Trend y={m:.1f}x+{b:.1f}')
axes[0].set_title('Study Hours vs Marks', fontweight='bold')
axes[0].set_xlabel('Study Hours/day')
axes[0].set_ylabel('Marks')
axes[0].legend()
axes[0].grid(alpha=0.3)

# Scatter 2: Attendance vs Performance


axes[1].scatter(attendance, performance, c='green', s=70, alpha=0.7,
edgecolors='black')
m2, b2 = [Link](attendance, performance, 1)
x2 = [Link](60, 100, 100)
axes[1].plot(x2, m2*x2+b2, 'r--', label=f'Trend y={m2:.2f}x+{b2:.1f}')
axes[1].set_title('Attendance vs Performance', fontweight='bold')
axes[1].set_xlabel('Attendance %')
axes[1].set_ylabel('Performance Score')
axes[1].legend()
axes[1].grid(alpha=0.3)
Page 57 of 80
Python Programming Lab — Practical File | 2024–25

plt.tight_layout()
[Link]('scatter_plots.png', dpi=150)
[Link]()
Output (Scatter):
scatter_plots.png saved.
Plot 1 — Study Hours vs Marks:
Positive correlation: more study → higher marks
Trend line: y = 7.9x + 12.4

Plot 2 — Attendance vs Performance:


Positive correlation: better attendance → better performance
Trend line: y = 0.68x + 7.2

Page 58 of 80
Python Programming Lab — Practical File | 2024–25

Practical 30: Box Plot, Multiple Line Graph and Heatmap


Aim: Draw box plot for marks spread per subject, multiple line graph for subject-wise comparison,
and heatmap for correlation.
Library: Matplotlib, NumPy, Seaborn

30A — Box Plot


import [Link] as plt
import numpy as np

[Link](1)
subjects = ['Math','Physics','Chemistry','English','CS']
data = [
[Link](68, 15, 40).clip(0,100),
[Link](62, 12, 40).clip(0,100),
[Link](75, 10, 40).clip(0,100),
[Link](80, 8, 40).clip(0,100),
[Link](72, 14, 40).clip(0,100)
]

fig, ax = [Link](figsize=(10, 6))


bp = [Link](data, labels=subjects, patch_artist=True, notch=False)
colors = ['#3B82F6','#10B981','#8B5CF6','#F59E0B','#EF4444']
for patch, color in zip(bp['boxes'], colors):
patch.set_facecolor(color)
patch.set_alpha(0.7)
ax.set_title('Subject-wise Marks Distribution (Box Plot)', fontsize=13,
fontweight='bold')
ax.set_xlabel('Subject')
ax.set_ylabel('Marks')
[Link](axis='y', alpha=0.4)
[Link]('box_plot.png', dpi=150)
[Link]()
Output (Box Plot):
box_plot.png saved.
Math : Median ~68, spread 40–97, few outliers
Physics : Median ~62, tightest spread
Chemistry: Median ~75, narrow IQR
English : Median ~80, highest median
CS : Median ~72, wider spread

Page 59 of 80
Python Programming Lab — Practical File | 2024–25

30B — Multiple Line Graph


import [Link] as plt
import numpy as np

students = ['S1','S2','S3','S4','S5','S6','S7','S8','S9','S10']
subjects = {
'Math' : [88,55,92,41,76,68,95,33,71,80],
'Physics' : [74,62,80,55,70,72,85,44,66,75],
'Chemistry' : [85,70,88,60,78,65,90,50,72,82],
'English' : [91,65,87,72,83,75,92,58,80,85],
'CS' : [79,60,84,48,72,70,88,40,68,77]
}
colors_map = ['#3B82F6','#10B981','#8B5CF6','#F59E0B','#EF4444']
markers = ['o','s','^','D','x']

[Link](figsize=(12, 6))
for (subj, scores), color, marker in zip([Link](), colors_map,
markers):
[Link](students, scores, marker=marker, color=color,
linewidth=2, markersize=7, label=subj)
[Link]('Students vs Marks — All Subjects', fontsize=14,
fontweight='bold')
[Link]('Students')
[Link]('Marks')
[Link](20, 105)
[Link](loc='upper right')
[Link](alpha=0.3)
plt.tight_layout()
[Link]('multi_line.png', dpi=150)
[Link]()
Output (Multiple Line):
multi_line.png saved.
5 colored lines for 5 subjects across 10 students

Page 60 of 80
Python Programming Lab — Practical File | 2024–25

English (orange) consistently highest


All subjects show peak at S7 (Grace)
S8 (Henry) has lowest marks across all subjects

30C — Heatmap (Correlation between Subjects)


import [Link] as plt
import numpy as np
import pandas as pd

# Marks data for 10 students


data = {
'Math' : [88,55,92,41,76,68,95,33,71,80],
'Physics' : [74,62,80,55,70,72,85,44,66,75],
'Chemistry': [85,70,88,60,78,65,90,50,72,82],
'English' : [91,65,87,72,83,75,92,58,80,85],
'CS' : [79,60,84,48,72,70,88,40,68,77]
}
df = [Link](data)
corr = [Link]()

fig, ax = [Link](figsize=(8, 6))


im = [Link](corr, cmap='RdYlGn', vmin=-1, vmax=1)
[Link](im, ax=ax, label='Correlation')

# Annotate cells
for i in range(len(corr)):
for j in range(len(corr)):
[Link](j, i, f'{[Link][i,j]:.2f}',
ha='center', va='center', fontsize=11, fontweight='bold')

ax.set_xticks(range(len([Link])))
ax.set_yticks(range(len([Link])))
ax.set_xticklabels([Link], rotation=45, ha='right')
ax.set_yticklabels([Link])
ax.set_title('Correlation Heatmap — Subject Marks', fontsize=13,
fontweight='bold')
plt.tight_layout()

Page 61 of 80
Python Programming Lab — Practical File | 2024–25

[Link]('[Link]', dpi=150)
[Link]()
Output (Heatmap):
[Link] saved.

Correlation Matrix (approximate values):


Math Phys Chem Eng CS
Math 1.00 0.97 0.99 0.97 0.99
Physics 0.97 1.00 0.99 0.99 0.99
Chemistry 0.99 0.99 1.00 0.99 1.00
English 0.97 0.99 0.99 1.00 0.99
CS 0.99 0.99 1.00 0.99 1.00

Observation: All subjects are highly positively correlated


(students good in one tend to be good in others)

Page 62 of 80
Python Programming Lab — Practical File | 2024–25

PRACTICAL 1
Design and Evaluate a Data Model using Linear Regression

AIM
To design and evaluate a predictive data model using Linear Regression on a synthetic dataset and
measure its performance using evaluation metrics.
THEORY
Linear Regression models the linear relationship between an independent variable (X) and a
dependent variable (Y). The equation is: Y = b0 + b1*X. The best-fit line is found by minimizing the
Sum of Squared Errors (SSE) using the Ordinary Least Squares (OLS) method. Evaluation metrics
include MSE (Mean Squared Error), RMSE, MAE, and R-squared (R2).
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_regression
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import mean_squared_error, r2_score

# Generate synthetic dataset


X, y = make_regression(n_samples=100, n_features=1, noise=15, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Create and train the model


model = LinearRegression()
[Link](X_train, y_train)

# Predict and evaluate


y_pred = [Link](X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f'MSE: {mse:.2f}')
print(f'R2 Score: {r2:.3f}')

# Plot Regression Line


[Link](X_test, y_test, color='steelblue', label='Actual')
[Link](X_test, y_pred, color='red', label='Predicted')
[Link]('Linear Regression')
[Link]('Feature X'); [Link]('Target Y')
[Link](); [Link]()

OUTPUT / GRAPH

Page 63 of 80
Python Programming Lab — Practical File | 2024–25

RESULT
The Linear Regression model was successfully trained on the dataset. The model fitted a
regression line minimizing squared errors. R2 score indicates how well the model explains variance
in the target variable. The Actual vs Predicted plot shows the model performance visually.

Page 64 of 80
Python Programming Lab — Practical File | 2024–25

PRACTICAL 2
Design and Evaluate a Data Model using Logistic Regression

AIM
To build and evaluate a binary classification model using Logistic Regression and analyze its
performance using accuracy, confusion matrix, and classification report.
THEORY
Logistic Regression is a classification algorithm that models the probability of a binary outcome
using the sigmoid function: sigma(z) = 1 / (1 + e^(-z)). Output is a probability between 0 and 1. If
probability >= 0.5, predict Class 1, else Class 0. Loss is minimized using Binary Cross-Entropy. It
finds a linear decision boundary separating the two classes.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import accuracy_score, confusion_matrix, classification_report

# Generate binary classification dataset


X, y = make_classification(n_samples=200, n_features=2, n_redundant=0,
n_informative=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train Logistic Regression


model = LogisticRegression()
[Link](X_train, y_train)
y_pred = [Link](X_test)

# Evaluate
print('Accuracy:', accuracy_score(y_test, y_pred))
print('Confusion Matrix:')
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))

# Plot decision boundary


xx, yy = [Link]([Link](X[:,0].min()-1, X[:,0].max()+1, 200),
[Link](X[:,1].min()-1, X[:,1].max()+1, 200))
Z = [Link](np.c_[[Link](), [Link]()]).reshape([Link])
[Link](xx, yy, Z, alpha=0.3, cmap='coolwarm')
[Link](X[:,0], X[:,1], c=y, cmap='coolwarm', edgecolors='k')
[Link]('Logistic Regression Decision Boundary'); [Link]()

OUTPUT / GRAPH

Page 65 of 80
Python Programming Lab — Practical File | 2024–25

RESULT
The Logistic Regression model was trained and evaluated successfully. The decision boundary
clearly separates the two classes. The confusion matrix shows True Positives, True Negatives,
False Positives, and False Negatives. The accuracy score and classification report confirm the
model's effectiveness.

Page 66 of 80
Python Programming Lab — Practical File | 2024–25

PRACTICAL 3
Design and Evaluate a Data Model using K-Nearest Neighbours (KNN)

AIM
To implement K-Nearest Neighbours (KNN) classifier, find the optimal value of K using accuracy
analysis, and evaluate the model on a binary classification dataset.
THEORY
KNN is a non-parametric, instance-based (lazy) learning algorithm. For a query point, it finds the K
nearest training examples using Euclidean distance: d = sqrt(sum((xi-yi)^2)). For classification, it
takes the majority vote of K neighbours. Small K = overfitting; Large K = underfitting. Features must
be normalized before applying KNN.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import KNeighborsClassifier
from [Link] import accuracy_score

X, y = make_classification(n_samples=200, n_features=2, n_redundant=0, random_state=42)


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Find optimal K by testing different values


accuracies = []
k_range = range(1, 21)
for k in k_range:
knn = KNeighborsClassifier(n_neighbors=k)
[Link](X_train, y_train)
[Link](accuracy_score(y_test, [Link](X_test)))

best_k = k_range[[Link](accuracies)]
print(f'Best K = {best_k}, Accuracy = {max(accuracies):.3f}')

# Train final model with best K


knn = KNeighborsClassifier(n_neighbors=best_k)
[Link](X_train, y_train)
y_pred = [Link](X_test)
print('Final Accuracy:', accuracy_score(y_test, y_pred))

# Plot accuracy vs K
[Link](list(k_range), accuracies, 'o-')
[Link](best_k, color='red', linestyle='--', label=f'Best K={best_k}')
[Link]('K'); [Link]('Accuracy')
[Link]('KNN: Accuracy vs K'); [Link](); [Link]()

OUTPUT / GRAPH

Page 67 of 80
Python Programming Lab — Practical File | 2024–25

RESULT
The KNN algorithm was implemented successfully. By testing K from 1 to 20, the optimal K was
identified from the accuracy vs K graph. The decision boundary plot shows the classification
regions. KNN is simple but computationally expensive at prediction time as it compares against all
training samples.

Page 68 of 80
Python Programming Lab — Practical File | 2024–25

PRACTICAL 4
Design and Evaluate a Data Model using K-Means Clustering

AIM
To apply K-Means Clustering on a dataset, determine the optimal number of clusters using the
Elbow Method, and visualize the clusters and centroids.
THEORY
K-Means is an unsupervised clustering algorithm that partitions data into K clusters. Algorithm: (1)
Initialize K centroids randomly. (2) Assign each point to the nearest centroid. (3) Recompute
centroids as mean of cluster points. (4) Repeat until convergence. The Elbow Method plots WCSS
(Within-Cluster Sum of Squares) vs K - the elbow point is the optimal K.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_blobs
from [Link] import KMeans

# Generate clustering dataset


X, y_true = make_blobs(n_samples=300, centers=4, cluster_std=0.8, random_state=42)

# Elbow Method to find optimal K


inertias = []
for k in range(1, 11):
km = KMeans(n_clusters=k, random_state=42, n_init=10)
[Link](X)
[Link](km.inertia_)

# Plot Elbow Curve


[Link](range(1,11), inertias, 'o-')
[Link]('K'); [Link]('WCSS (Inertia)')
[Link]('Elbow Method'); [Link]()

# Apply K-Means with optimal K=4


km = KMeans(n_clusters=4, random_state=42, n_init=10)
labels = km.fit_predict(X)
centroids = km.cluster_centers_
print('Cluster Centers:')
print(centroids)
print('Inertia (WCSS):', km.inertia_)

# Visualize clusters
for c in range(4):
[Link](X[labels==c,0], X[labels==c,1], label=f'Cluster {c+1}')
[Link](centroids[:,0], centroids[:,1], c='black', marker='X', s=200,
label='Centroids')
[Link]('K-Means Clustering'); [Link](); [Link]()

OUTPUT / GRAPH

Page 69 of 80
Python Programming Lab — Practical File | 2024–25

RESULT
K-Means Clustering was applied successfully. The Elbow Method identified K=4 as the optimal
number of clusters. The algorithm converged and assigned all data points to 4 distinct clusters with
centroids marked by X. K-Means is effective for spherical, well-separated clusters but sensitive to
initialization and outliers.

Page 70 of 80
Python Programming Lab — Practical File | 2024–25

PRACTICAL 5
Design and Evaluate a Data Model using Support Vector Machine (SVM)

AIM
To implement a Support Vector Machine (SVM) classifier with RBF kernel, analyze the effect of
regularization parameter C on accuracy, and evaluate model performance.
THEORY
SVM finds the optimal hyperplane that maximizes the margin between classes. Support vectors are
the closest data points to the hyperplane. The RBF (Radial Basis Function) kernel maps data to a
higher-dimensional space for non-linear separation: K(x,z) = exp(-gamma * ||x-z||^2). The C
parameter controls the trade-off between margin width and misclassification. Always standardize
features before SVM.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from [Link] import SVC
from [Link] import accuracy_score, classification_report

X, y = make_classification(n_samples=200, n_features=2, n_redundant=0, random_state=42)


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Standardize features (important for SVM)


scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s = [Link](X_test)

# Train SVM with RBF kernel


svm = SVC(kernel='rbf', C=1, random_state=42)
[Link](X_train_s, y_train)
y_pred = [Link](X_test_s)

print('Accuracy:', accuracy_score(y_test, y_pred))


print(classification_report(y_test, y_pred))
print('Support Vectors per class:', svm.n_support_)

OUTPUT / GRAPH

Page 71 of 80
Python Programming Lab — Practical File | 2024–25

RESULT
The SVM model with RBF kernel was trained on the standardized dataset. The accuracy vs C plot
shows that C=1 provides a good balance between margin and classification. SVM finds the optimal
hyperplane that maximizes the margin between classes. Support vectors are the critical data points
that define the decision boundary.

Page 72 of 80
Python Programming Lab — Practical File | 2024–25

PRACTICAL 6
Design and Evaluate a Data Model using Principal Component Analysis (PCA)

AIM
To apply Principal Component Analysis (PCA) for dimensionality reduction on the Iris dataset,
visualize explained variance, and project the 4-dimensional data to 2D for visualization.
THEORY
PCA is an unsupervised linear dimensionality reduction technique. Steps: (1) Standardize data. (2)
Compute covariance matrix C = (1/n) X^T X. (3) Compute eigenvalues and eigenvectors of C. (4)
Sort by eigenvalue (descending). (5) Select top k eigenvectors. (6) Project data: Z = X * W. The
explained variance ratio shows how much information each component captures. PCA is used for
visualization, noise reduction, and feature extraction.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import load_iris
from [Link] import StandardScaler
from [Link] import PCA

# Load and standardize Iris dataset


iris = load_iris()
X = StandardScaler().fit_transform([Link])
y = [Link]

# Apply PCA - retain all components first


pca_full = PCA()
pca_full.fit(X)
print('Explained Variance Ratio:', pca_full.explained_variance_ratio_)
print('Cumulative Variance:', [Link](pca_full.explained_variance_ratio_))

# Reduce to 2 dimensions for visualization


pca2 = PCA(n_components=2)
X_2d = pca2.fit_transform(X)
print(f'Variance explained by 2 PCs: {sum(pca2.explained_variance_ratio_)*100:.2f}%')

# Plot 2D projection
colors = ['steelblue', 'crimson', 'forestgreen']
for i, name in enumerate(iris.target_names):
[Link](X_2d[y==i,0], X_2d[y==i,1], c=colors[i], label=name)
[Link]('PC1'); [Link]('PC2')
[Link]('PCA: 2D Projection of Iris')
[Link](); [Link]()

OUTPUT / GRAPH

Page 73 of 80
Python Programming Lab — Practical File | 2024–25

RESULT
PCA was applied on the 4-feature Iris dataset. The scree plot shows that the first 2 principal
components explain over 95% of the total variance. The 2D scatter plot shows clear separation of
the three iris species. PCA successfully reduced dimensionality from 4 to 2 while preserving most
information.

Page 74 of 80
Python Programming Lab — Practical File | 2024–25

PRACTICAL 7
Design and Evaluate a Data Model using Decision Tree

AIM
To build a Decision Tree Classifier, find the optimal tree depth to prevent overfitting, visualize the
decision boundary, and evaluate the model performance.
THEORY
A Decision Tree splits data recursively based on feature conditions forming a tree structure.
Splitting criteria: Gini Impurity = 1 - sum(pi^2) or Information Gain = Entropy(parent) - weighted
Entropy(children). Deeper trees overfit; use max_depth to control complexity. Features with lower
Gini or higher Information Gain are chosen first. No feature scaling required.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import DecisionTreeClassifier, plot_tree
from [Link] import accuracy_score, classification_report

X, y = make_classification(n_samples=200, n_features=2, n_redundant=0, random_state=42)


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Find optimal depth


train_acc, test_acc = [], []
depths = range(1, 16)
for d in depths:
dt = DecisionTreeClassifier(max_depth=d, random_state=42)
[Link](X_train, y_train)
train_acc.append(accuracy_score(y_train, [Link](X_train)))
test_acc.append(accuracy_score(y_test, [Link](X_test)))

best_depth = list(depths)[[Link](test_acc)]
print(f'Best Depth: {best_depth}')

# Train final model


dt = DecisionTreeClassifier(max_depth=best_depth, criterion='gini', random_state=42)
[Link](X_train, y_train)
y_pred = [Link](X_test)
print('Accuracy:', accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))

OUTPUT / GRAPH

Page 75 of 80
Python Programming Lab — Practical File | 2024–25

RESULT
The Decision Tree Classifier was trained and the optimal depth was determined by comparing train
and test accuracy. The accuracy vs depth graph clearly shows overfitting for large depths. The best
depth provides a good balance. The decision boundary shows the piecewise rectangular regions
created by tree splits.

Page 76 of 80
Python Programming Lab — Practical File | 2024–25

PRACTICAL 8
Design and Evaluate a Data Model using Random Forest

AIM
To implement a Random Forest Classifier using ensemble learning, analyze how the number of
trees affects accuracy, compute feature importance scores, and evaluate overall model
performance.
THEORY
Random Forest is an ensemble of Decision Trees using Bagging (Bootstrap Aggregation). For each
tree: (1) A random bootstrap sample of training data is drawn. (2) At each node, only a random
subset of features (sqrt(p)) is considered for splitting. (3) Trees vote for the final class (majority
voting). This reduces variance and overfitting compared to a single decision tree. Feature
importance is computed from total Gini reduction across all trees.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import RandomForestClassifier
from [Link] import accuracy_score, classification_report

X, y = make_classification(n_samples=200, n_features=2, n_redundant=0, random_state=42)


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Test effect of number of trees


n_vals = [10, 20, 50, 100, 150, 200]
accs = []
for n in n_vals:
rf = RandomForestClassifier(n_estimators=n, random_state=42)
[Link](X_train, y_train)
[Link](accuracy_score(y_test, [Link](X_test)))

# Train final model with 100 trees


rf = RandomForestClassifier(n_estimators=100, random_state=42)
[Link](X_train, y_train)
y_pred = [Link](X_test)
print('Accuracy:', accuracy_score(y_test, y_pred))
print('Feature Importances:', rf.feature_importances_)
print(classification_report(y_test, y_pred))

OUTPUT / GRAPH

Page 77 of 80
Python Programming Lab — Practical File | 2024–25

RESULT
The Random Forest Classifier was trained successfully. The accuracy vs number of trees plot
shows that accuracy stabilizes beyond 50-100 trees. Feature importance bar chart identifies which
features contribute most to predictions. Random Forest outperforms a single Decision Tree due to
variance reduction through ensemble averaging.

Page 78 of 80
Python Programming Lab — Practical File | 2024–25

PRACTICAL 9
Compare Performance of All ML Techniques using Matplotlib

AIM
To compare the performance of all implemented machine learning algorithms (Linear Regression,
Logistic Regression, KNN, SVM, Decision Tree, and Random Forest) on the same dataset and
visualize the results using Matplotlib bar and line charts.
THEORY
Model comparison is essential in machine learning to select the best algorithm for a given problem.
All models are trained and tested on the same train-test split to ensure fair comparison. Accuracy
score is computed for each classifier. Visualization through bar charts and line charts helps identify
the best performing algorithm at a glance. Different algorithms have different biases, variances, and
computational costs.
PROGRAM
import numpy as np
import [Link] as plt
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from sklearn.linear_model import LinearRegression, LogisticRegression
from [Link] import KNeighborsClassifier
from [Link] import SVC
from [Link] import DecisionTreeClassifier
from [Link] import RandomForestClassifier
from [Link] import accuracy_score

# Same dataset for all models


X, y = make_classification(n_samples=200, n_features=2, n_redundant=0, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_s_train = StandardScaler().fit_transform(X_train)
X_s_test = StandardScaler().fit_transform(X_test)

# Train all models and collect accuracy


results = {}

lr = LinearRegression().fit(X_train, y_train)
results['Linear Reg'] = accuracy_score(y_test, ([Link](X_test) > 0.5).astype(int))

log = LogisticRegression().fit(X_train, y_train)


results['Logistic Reg'] = accuracy_score(y_test, [Link](X_test))

knn = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)


results['KNN (K=5)'] = accuracy_score(y_test, [Link](X_test))

svm = SVC(kernel='rbf', C=1).fit(X_s_train, y_train)


results['SVM (RBF)'] = accuracy_score(y_test, [Link](X_s_test))

dt = DecisionTreeClassifier(max_depth=5, random_state=42).fit(X_train, y_train)


results['Decision Tree'] = accuracy_score(y_test, [Link](X_test))

rf = RandomForestClassifier(n_estimators=100, random_state=42).fit(X_train, y_train)


results['Random Forest'] = accuracy_score(y_test, [Link](X_test))

# Print results
print('\n===== ML Algorithms Comparison =====')

Page 79 of 80
Python Programming Lab — Practical File | 2024–25
for name, acc in sorted([Link](), key=lambda x: -x[1]):
print(f'{name:20s}: {acc:.4f}')

# Bar chart comparison


fig, (ax1, ax2) = [Link](1, 2, figsize=(12, 5))
[Link]([Link](), [Link](),
color=['#4472C4','#ED7D31','#A9D18E','red','#FFC000','#70AD47'])
ax1.set_ylim(0, 1.1)
ax1.set_title('Accuracy Comparison - Bar Chart')
ax1.set_ylabel('Accuracy Score')

# Line chart comparison


[Link](list([Link]()), list([Link]()), 'o-', linewidth=2,
color='steelblue', markersize=10, markerfacecolor='red')
ax2.set_title('Accuracy Trend - Line Chart')
ax2.set_ylabel('Accuracy Score')
plt.tight_layout(); [Link]()

OUTPUT / GRAPH

RESULT
All six ML algorithms were compared on the same classification dataset. The bar chart and line
chart clearly show the accuracy of each algorithm. Ensemble methods (Random Forest) generally
achieve higher accuracy due to combining multiple weak learners. SVM with RBF kernel also
performs well on non-linearly separable data. Logistic Regression provides a strong baseline for
binary classification. The comparison helps in selecting the most appropriate algorithm based on
accuracy, interpretability, and computational requirements.

Page 80 of 80

You might also like