0% found this document useful (0 votes)
4 views72 pages

Python Practical Complete Final

The document contains a series of practical programming exercises in Python focused on various algorithms and data manipulations, including palindrome checks, prime number checks, and Fibonacci series generation. It also covers NumPy functionalities such as array creation, operations, broadcasting, and boolean indexing. Each practical includes a clear aim, program code, and expected output.

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)
4 views72 pages

Python Practical Complete Final

The document contains a series of practical programming exercises in Python focused on various algorithms and data manipulations, including palindrome checks, prime number checks, and Fibonacci series generation. It also covers NumPy functionalities such as array creation, operations, broadcasting, and boolean indexing. Each practical includes a clear aim, program code, and expected output.

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

ML&DA using Python 2024-

2026

Practical 1: Palindrome Number Check

Aim: Write a program to determine whether a number is palindrome or


not.

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

Page 1 of 72
ML&DA using Python 2024-
2026

Practical 2: Prime Number Check

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

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

Page 2 of 72
ML&DA using Python 2024-
2026

Practical 3: Sum of Digits

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

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

Page 3 of 72
ML&DA using Python 2024-
2026

Practical 4: Sum of First N Positive Integers

Aim: Write a program to find the sum of first n positive integer


numbers.

Program
# Sum of first n positive integers
n = int(input('Enter value of n: '))
# Method 1: Formula
total_formula = n * (n + 1) // 2
# Method 2: 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

Page 4 of 72
ML&DA using Python 2024-
2026

Practical 5: Fibonacci Series

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


13…

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

Page 5 of 72
ML&DA using Python 2024-
2026

Practical 6: Factorial of a Number

Aim: Write a program to compute factorial of a number.

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:
print(f'{num}! = {factorial(num)}')

Output

Page 6 of 72
ML&DA using Python 2024-
2026

Practical 7: Armstrong Number Check

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


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

Page 7 of 72
ML&DA using Python 2024-
2026

Practical 8: HCF of Given Numbers

Aim: Write a program to compute HCF (Highest Common Factor) of given


numbers.

Program
# HCF 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: '))
print(f'HCF of {a} and {b} = {hcf(a, b)}')

# Multiple numbers using reduce


import math
from functools import reduce
nums = list(map(int, input('Enter numbers (space-separated):
').split()))
print(f'HCF of {nums} = {reduce([Link], nums)}')

Output

Page 8 of 72
ML&DA using Python 2024-
2026

Practical 9: Age Group Counter (50–60)

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

Program
# Count persons in age group 50 to 60
import random
[Link](42) # reproducible results
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'Total persons : 100')
print(f'Persons aged 50-60 : {count}')
print(f'Percentage : {count}%')

Output

Page 9 of 72
ML&DA using Python 2024-
2026

Practical 10: Decimal to Binary Conversion

Aim: Write a program to read a positive integer and print its binary
equivalent.

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

Page 10 of 72
ML&DA using Python 2024-
2026

Page 11 of 72
ML&DA using Python 2024-
2026

Practical 11: Creating NumPy Arrays

Aim: Learn various ways to create NumPy arrays – from lists,


specific values, ranges, random, empty, and patterns.

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

# 2. Specific value arrays


zeros = [Link]((3, 3)) # all zeros
ones = [Link]((2, 4)) # all ones
full = [Link]((3, 3), 7) # filled with 7
eye = [Link](4) # identity matrix

# 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 of 5

# 4. Array attributes
a = [Link]([[1,2,3],[4,5,6]])
print('Shape :', [Link]) # (2,3)
print('Size :', [Link]) # 6
print('Ndim :', [Link]) # 2
print('Dtype :', [Link]) # int64
print('Itemsize :', [Link]) # 8 bytes
print('Nbytes :', [Link]) # 48 bytes

Page 12 of 72
ML&DA using Python 2024-
2026

Output

Page 13 of 72
ML&DA using Python 2024-
2026

Practical 12: NumPy Array Operations

Aim: Perform arithmetic, mathematical, aggregation, manipulation,


logical, sorting, and linear algebra operations.

Program
import numpy as np
a = [Link]([10, 20, 30, 40, 50])
b = [Link]([ 1, 2, 3, 4, 5])

# Arithmetic (element-wise)
print('Add :', a + b) # [11 22 33 44 55]
print('Mul :', a * b) # [10 40 90 160 250]
print('Pow :', b ** 3) # [1 8 27 64 125]

# Aggregation
print('Sum:', [Link](a)) # 150
print('Mean:', [Link](a)) # 30.0
print('Std:', [Link](a)) # 14.142
print('Cumsum:', [Link](b)) # [1 3 6 10 15]

# Sorting & Searching


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

# Linear Algebra
A = [Link]([[1,2],[3,4]])
B = [Link]([[5,6],[7,8]])
print('Dot:\n', [Link](A, B))
print('Det:', [Link](A))
vals, _ = [Link](A)
print('Eigenvalues:', vals)

Page 14 of 72
ML&DA using Python 2024-
2026

Output

Page 15 of 72
ML&DA using Python 2024-
2026

Practical 13: Universal Functions (ufuncs)

Aim: Understand and demonstrate Universal Functions (ufuncs), their


key features, advantages, and vectorized operations.

Program
import numpy as np
import time

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


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

# Key features
print('Reduce(add) :', [Link](arr)) # 15.0
print('Accumulate(add):', [Link](arr)) # [1 3 6
10 15]
print('Outer product:\n', [Link]([1,2,3],
[1,2,3]))

# Speed comparison
large = [Link](1_000_000)
t0 = [Link]()
_ = [x**2 for x in large] # Python loop
loop_t = [Link]() - t0
t0 = [Link]()
_ = [Link](large) # ufunc
ufunc_t = [Link]() - t0
print(f'Python loop : {loop_t:.4f}s')
print(f'NumPy ufunc : {ufunc_t:.4f}s')
print(f'Speedup : {loop_t/ufunc_t:.1f}x faster')

Page 16 of 72
ML&DA using Python 2024-
2026

Output

Page 17 of 72
ML&DA using Python 2024-
2026

Practical 14: Broadcasting in NumPy

Aim: Understand the rules of broadcasting and apply them in array


operations.

Program
import numpy as np
arr = [Link]([[1,2,3],[4,5,6],[7,8,9]])

# Rule 1: Scalar broadcast


print('Matrix + 10:\n', arr + 10)

# Rule 2: Row-wise 1D broadcast


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

# Rule 3: Column broadcast


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

# Error and fix


x = [Link]([[1,2,3],[4,5,6]]) # shape (2,3)
y = [Link]([1,2]) # shape (2,)
try:
print(x + y)
except ValueError as e:
print('Error:', e)
# Fix: reshape to column vector
print('Fixed:\n', x + [Link](2,1))

Page 18 of 72
ML&DA using Python 2024-
2026

Output

Page 19 of 72
ML&DA using Python 2024-
2026

Practical 15: Indexing, Slicing, and Iterating

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


arrays.

Program
import numpy as np

# 1D Indexing & Slicing


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

# 2D Indexing & Slicing


m = [Link]([[1,2,3,4],[5,6,7,8],[9,10,11,12],
[13,14,15,16]])
print('m[0] :', m[0]) # first row
print('m[:,0] :', m[:,0]) # first column
print('m[1,2] :', m[1,2]) # element
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 col

# Iteration using nditer


for elem in [Link](m):
print(elem, end=' ')

Page 20 of 72
ML&DA using Python 2024-
2026

Output

Page 21 of 72
ML&DA using Python 2024-
2026

Practical 16: Boolean Indexing & Conditional Filtering

Aim: Apply boolean indexing and conditional filtering on 1D and 2D


NumPy arrays.
Program
import numpy as np
a = [Link]([15, 3, 72, 45, 88, 12, 55, 9, 60, 24])

# Boolean mask
mask_gt40 = a > 40
print('Mask >40 :', mask_gt40)
print('Values>40:', a[mask_gt40]) # [72 45 88 55 60]

# Conditional filtering
print('Even :', a[a % 2 == 0]) # even numbers
print('20-60 :', a[(a>=20)&(a<=60)]) # between 20 and 60
print('<20|>70 :', a[(a<20)|(a>70)]) # <20 OR >70

# Modify with mask


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

# Count and locate


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

Output

Page 22 of 72
ML&DA using Python 2024-
2026

Page 23 of 72
ML&DA using Python 2024-
2026

Practical 17: Fancy Indexing in NumPy

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

Program
import numpy as np

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

# 2D fancy indexing
m = [Link](1, 26).reshape(5, 5)
print('Rows 0,2,4:\n', m[[0, 2, 4]])

# Row, col pairs


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

# Cross-product with ix_


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

# Sort by fancy indexing


scores = [Link]([85, 42, 90, 67, 78])
ranked = [Link](scores)[::-1]
print('Sorted desc:', scores[ranked]) # [90 85 78 67 42]

Output

Page 24 of 72
ML&DA using Python 2024-
2026

Practical 18: Reshaping Arrays

Aim: Change array dimensions, add/remove dimensions, combine and


split arrays.

Program
import numpy as np

arr = [Link](1, 25)


print('4x6:\n', [Link](4, 6))
print('6x-1:\n', [Link](6, -1)) # -1 auto-calc

# Adding dimensions
a = [Link]([1, 2, 3])
print('newaxis row:', a[[Link],:].shape) # (1,3)
print('newaxis col:', a[:,[Link]].shape) # (3,1)

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

# Flatten vs Ravel
m = [Link]([[1,2,3],[4,5,6]])
print('flatten:', [Link]()) # always returns copy
print('ravel :', [Link]()) # returns view if possible

# Stacking
x = [Link]([[1,2],[3,4]])
y = [Link]([[5,6],[7,8]])
print('vstack:\n', [Link]([x, y]))
print('hstack:\n', [Link]([x, y]))

Page 25 of 72
ML&DA using Python 2024-
2026

Output

Page 26 of 72
ML&DA using Python 2024-
2026

Practical 19: NumPy

Aim: Comprehensive NumPy exercises: array creation, arithmetic,


broadcasting, boolean indexing, reshaping, sorting, and linear
algebra.

Program
import numpy as np

# Exercise 1: Creation & Attributes


a = [Link](10, 51)
b = [Link](0, 1, 10)
d = [Link](1, 100, (4, 5))
print('Shape:', [Link], '| Size:', [Link], '| Ndim:',
[Link])

# Exercise 2: Arithmetic
A = [Link]([[1,2,3],[4,5,6],[7,8,9]])
B = [Link]([[9,8,7],[6,5,4],[3,2,1]])
print('A@B:\n', A @ B)
print('Mean:', [Link](A), '| Std:', round([Link](A),4))

# Exercise 3: Broadcasting
M = [Link](float)
norm = (M - [Link]()) / ([Link]() - [Link]())
print('Normalized:\n', [Link](norm, 3))

# Exercise 7: Linear Algebra


LA = [Link]([[4,7],[2,6]])
print('Det:', [Link](LA))
b_vec = [Link]([23, 18])
sol = [Link](LA, b_vec)
print(f'Solve: x={sol[0]:.4f}, y={sol[1]:.4f}')

# Exercise 8: Student Marks Analysis


[Link](7)
marks = [Link](40, 100, (10, 5))
total = [Link](axis=1)
Page 27 of 72
ML&DA using Python 2024-
2026

topper = [Link](total)
print(f'Topper: S{topper+1} with {total[topper]} marks')

Output

Page 28 of 72
ML&DA using Python 2024-
2026

Practical 20: Pandas Series & DataFrame Introduction

Aim: Import Pandas, create Series from lists and dictionaries,


perform arithmetic operations, and access elements.

Program
import pandas as pd
import numpy as np

# Series from list (integer index)


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

# Series from dictionary (string labels)


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

# Arithmetic operations
print('s1 * 5:\n', s1 * 5)
print('s1 + s1:\n', s1 + s1)

# Accessing elements
print('First 3 :', s1[:3].tolist())
print('Last 2 :', s1[-2:].tolist())
print('Values>50:', s1[s1 > 50].tolist())

# Statistics
print('Mean:', [Link](), '| Max:', [Link]())
print('Sum :', [Link](), '| Std:', round([Link](),2))

Page 29 of 72
ML&DA using Python 2024-
2026

Output

Page 30 of 72
ML&DA using Python 2024-
2026

Practical 21: Pandas DataFrame Operations

Aim: Create a DataFrame with student data, display info, add/delete


columns, sort, and apply statistical functions.
Program
import pandas as pd

data = {
'Name' :
['Alice','Bob','Carol','David','Eve','Frank','Grace','Henry'
],
'Roll' : [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]())

# Add Grade column using apply()


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('With Grades:\n', df)

# Sort and statistics


print('Sorted Desc:\n', df.sort_values('Marks',
ascending=False))
print('Mean:', df['Marks'].mean(), '| Max:',
df['Marks'].max())
print('Describe:\n', df['Marks'].describe())

Page 31 of 72
ML&DA using Python 2024-
2026

Output

Page 32 of 72
ML&DA using Python 2024-
2026

Practical 22: Handling Missing Data in Pandas

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

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)

# Detect and count NaN


print('isnull():\n', [Link]())
print('Missing per col:\n', [Link]().sum())
print('Total missing:', [Link]().sum().sum())

# Fill with constant


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

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

Page 33 of 72
ML&DA using Python 2024-
2026

print('Fill with mean:\n', df_mean)

# Drop rows with any NaN


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

Output

Page 34 of 72
ML&DA using Python 2024-
2026

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.

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','Fin
ance'],
'Salary' :
[75000,45000,80000,62000,48000,72000,55000,42000,68000,70000
]
}
df = [Link](data)

grp = [Link]('Department')
print('Avg Salary:\n', grp['Salary'].mean())
print('Max Salary:\n', grp['Salary'].max())
print('Emp Count :\n', grp['Employee'].count())

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

# Filter: keep only high-paying depts


high = [Link](lambda x: x['Salary'].mean() > 50000)
print('Avg > 50000:\n', high)

Page 35 of 72
ML&DA using Python 2024-
2026

Output

Page 36 of 72
ML&DA using Python 2024-
2026

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

Aim: Create two DataFrames, perform inner/left/right/outer merge,


join, and concatenate.
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]
})

# Four types of merge


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('Inner Merge:\n', inner) # 3 matching rows


print('Left Merge :\n', left) # 5 rows, NaN for 104,105
print('Outer Merge:\n', outer) # 7 rows total

# Row concatenation
more = [Link]({'Roll':[108,109],'Name':
['Frank','Grace'],'City':['Jaipur','Kolkata']})
print('Concat:\n', [Link]([students,more],
ignore_index=True))

Page 37 of 72
ML&DA using Python 2024-
2026

Output

Page 38 of 72
ML&DA using Python 2024-
2026

Practical 25: Reading and Writing Data with Pandas

Aim: Read data from CSV, display info, save to CSV/Excel, export
selected columns and change delimiter.
Program
import pandas as pd, io

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

# Read CSV
df = pd.read_csv([Link](csv_data))
print('Data:\n', df)
print('Describe:\n', [Link]())
print('Dtypes:\n', [Link])

# Write CSV and Excel


df.to_csv('[Link]', index=False)
df.to_excel('[Link]', sheet_name='Sales', index=False)
print('Saved CSV and Excel!')

# Pipe delimiter
df.to_csv('[Link]', sep='|', index=False)
df2 = pd.read_csv('[Link]', sep='|')
print('Pipe re-read:\n', [Link]())

Page 39 of 72
ML&DA using Python 2024-
2026

Output

Page 40 of 72
ML&DA using Python 2024-
2026

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.

Program
import pandas as pd, numpy as np, io

orders_csv = '''OrderID,CustomerID,Category,Amount,City
1001,C01,Electronics,75000,Delhi
1002,C02,Clothing,3500,Mumbai
1003,C01,Electronics,25000,Delhi
1004,C03,Furniture,18000,Pune
1005,C04,Clothing,2200,Chennai
1006,,Electronics,32000,Delhi
1007,C05,Furniture,45000,Mumbai
1008,C02,Clothing,,Bangalore
1009,C06,Electronics,15000,Pune
1010,C04,Furniture,22000,Chennai'''

orders = pd.read_csv([Link](orders_csv))
print('Missing:\n', [Link]().sum())

# Handle NaN
orders['CustomerID'].fillna('Unknown', inplace=True)
orders['Amount'].fillna(orders['Amount'].median(),
inplace=True)

# Category-wise sales
cat = [Link]('Category')
['Amount'].sum().sort_values(ascending=False)
print('Category Sales:\n', cat)

# City-wise sales
city = [Link]('City')
['Amount'].sum().sort_values(ascending=False)
print('City Sales:\n', city)

Page 41 of 72
ML&DA using Python 2024-
2026

# Export summary
summary = [Link]('Category').agg(
Orders=('OrderID','count'), Total=('Amount','sum'),
Avg=('Amount','mean')
).round(2)
summary.to_csv('sales_summary.csv')
print(summary)

Output

Page 42 of 72
ML&DA using Python 2024-
2026

Practical 27: Line Graph using Matplotlib

Aim: Plot a line graph showing Student vs Marks and Study Hours
trend.

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

# Graph 1: Marks line with fill and average line


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

# Graph 2: Study Hours trend


axes[1].plot(students, study_hrs, marker='s', color='green',
linewidth=2, linestyle='-.')
axes[1].set_title('Study Hours Trend', fontweight='bold')
axes[1].set_xlabel('Student') ;
axes[1].set_ylabel('Hours/Day')

Page 43 of 72
ML&DA using Python 2024-
2026

axes[1].set_xticklabels(students, rotation=45)

plt.tight_layout()
[Link]('line_graph.png', dpi=150)
[Link]()

Output

Graph / Plot

Page 44 of 72
ML&DA using Python 2024-
2026

Practical 28: Bar Chart using Matplotlib

Aim: Plot bar charts comparing student marks and Alice's subject-
wise performance.

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

# Bar 1: Color-coded pass/fail bars


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].axhline(75, color='orange', linestyle='--',
label='Pass (75)')
axes[0].set_title('Students vs Math Marks',
fontweight='bold')
axes[0].set_ylim(0, 115) ; axes[0].legend()

# Bar 2: Alice's subject-wise marks


x = [Link](len(subjects))
colors2 =
['#0D9488','#2563EB','#8B5CF6','#F59E0B','#EC4899']
bars2 = axes[1].bar(x, alice_marks, color=colors2,
edgecolor='black', width=0.5)
axes[1].bar_label(bars2, padding=3)
axes[1].set_title("Alice's Marks by Subject",
Page 45 of 72
ML&DA using Python 2024-
2026

fontweight='bold')
axes[1].set_xticks(x) ; axes[1].set_xticklabels(subjects)
axes[1].set_ylim(0, 110)

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

Output

Graph / Plot

Page 46 of 72
ML&DA using Python 2024-
2026

Practical 29: Pie Chart, Histogram & Scatter Plot

Aim: Draw pie chart for marks distribution, histogram for score
distribution, and scatter plot for study hours vs marks.

Program
import [Link] as plt
import numpy as np

# ── Pie Chart
─────────────────────────────────────────────────
subjects = ['Math','Physics','Chemistry','English','CS']
marks = [88, 74, 85, 91, 79]
explode = [0, 0, 0, 0.08, 0] # highlight English
[Link](figsize=(7, 7))
[Link](marks, labels=subjects, explode=explode,
autopct='%1.1f%%', startangle=140, shadow=True)
[Link]("Alice's Marks Distribution", fontweight='bold')
[Link]('pie_chart.png', dpi=150) ; [Link]()

# ── Histogram
─────────────────────────────────────────────────
[Link](42)
scores = [Link]([[Link](70,10,60),
[Link](45,8,20),

[Link](90,5,20)]).astype(int)
scores = [Link](scores, 0, 100)
[Link](figsize=(9, 5))
[Link](scores, bins=15, edgecolor='black',
color='#3B82F6', alpha=0.8)
[Link]([Link](scores), color='red', linestyle='--',
label='Mean')
[Link]([Link](scores), color='green',
linestyle='-.', label='Median')
[Link]() ; [Link]('[Link]', dpi=150) ;
[Link]()

Page 47 of 72
ML&DA using Python 2024-
2026

# ── Scatter Plot
───────────────────────────────────────────────
[Link](5)
study = [Link](2, 10, 30)
marks2 = study * 8 + [Link](-10, 10, 30)
[Link](figsize=(7, 5))
[Link](study, marks2, c='blue', s=70, alpha=0.7)
m, b = [Link](study, marks2, 1)
[Link]([Link](2,9,100), m*[Link](2,9,100)+b,
'r--',
label=f'Trend y={m:.1f}x+{b:.1f}')
[Link]('Study Hours vs Marks') ; [Link]()
[Link]('scatter_plots.png', dpi=150) ; [Link]()

Output

Graph / Plot

Page 48 of 72
ML&DA using Python 2024-
2026

Page 49 of 72
ML&DA using Python 2024-
2026

Practical 30: Box Plot, Multi-Line Graph & Heatmap

Aim: Draw box plot for marks spread, multiple line graph for subject
comparison, and heatmap for correlation.

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

# ── Box Plot
──────────────────────────────────────────────────
[Link](1)
subjects = ['Math','Physics','Chemistry','English','CS']
data = [[Link](m,s,40).clip(0,100)
for m,s in [(68,15),(62,12),(75,10),(80,8),(72,14)]]
fig, ax = [Link](figsize=(10, 6))
bp = [Link](data, labels=subjects, patch_artist=True)
colors = ['#3B82F6','#10B981','#8B5CF6','#F59E0B','#EF4444']
for patch,c in zip(bp['boxes'],colors):
patch.set_facecolor(c) ; patch.set_alpha(0.7)
ax.set_title('Subject-wise Marks Distribution',
fontweight='bold')
[Link]('box_plot.png',dpi=150) ; [Link]()

# ── Multi-Line Graph
──────────────────────────────────────────
students =
['S1','S2','S3','S4','S5','S6','S7','S8','S9','S10']
subj_marks = {'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]}
[Link](figsize=(12, 6))
for subj,scores in subj_marks.items():
[Link](students, scores, linewidth=2, label=subj)
[Link]('Students vs Marks – All
Subjects',fontweight='bold')

Page 50 of 72
ML&DA using Python 2024-
2026

[Link]() ; [Link](alpha=0.3)
[Link]('multi_line.png',dpi=150) ; [Link]()

# ── Heatmap
───────────────────────────────────────────────────
df = [Link](subj_marks)
corr = [Link]()
fig,ax = [Link](figsize=(8,6))
im = [Link](corr, cmap='RdYlGn', vmin=-1, vmax=1)
[Link](im) ; ax.set_title('Correlation
Heatmap',fontweight='bold')
for i in range(len(corr)):
for j in range(len(corr)):

[Link](j,i,f'{[Link][i,j]:.2f}',ha='center',va='center',
fontweight='bold')
[Link]('[Link]',dpi=150) ; [Link]()

Output

Graph / Plot

Page 51 of 72
ML&DA using Python 2024-
2026

Page 52 of 72
ML&DA using Python 2024-
2026

Practical 31: Linear Regression – Design & Evaluate

Aim: Design and evaluate a predictive data model using Linear


Regression on a synthetic dataset.

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)

# Train 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}')
print(f'Coeff : {model.coef_[0]:.4f}')
print(f'Intercept: {model.intercept_:.4f}')

# Plot Actual vs Predicted


[Link](figsize=(10, 4))
[Link](X_test, y_test, color='steelblue',
label='Actual', s=50)
[Link](X_test, y_pred, color='red', label='Predicted',
linewidth=2)

Page 53 of 72
ML&DA using Python 2024-
2026

[Link]('Linear Regression – Actual vs Predicted',


fontweight='bold')
[Link]('Feature X') ; [Link]('Target Y')
[Link]() ; [Link](alpha=0.3)
[Link]('ml_p1_linear_reg.png', dpi=150)
[Link]()

Output

Graph / Plot

Page 54 of 72
ML&DA using Python 2024-
2026

Practical 32: Logistic Regression – Binary Classification

Aim: Build and evaluate a binary classification model using Logistic


Regression.

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

Page 55 of 72
ML&DA using Python 2024-
2026

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',
fontweight='bold')
[Link]('ml_p2_logistic_reg.png', dpi=150)
[Link]()

Output

Graph / Plot

Page 56 of 72
ML&DA using Python 2024-
2026

Practical 33: K-Nearest Neighbours (KNN)

Aim: Implement KNN classifier, find optimal K using accuracy


analysis, and evaluate performance.

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 K=1 to 20


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 = list(k_range)[[Link](accuracies)]
print(f'Best K={best_k}, Accuracy={max(accuracies):.3f}')

# Train final model


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

# Plot Accuracy vs K
[Link](figsize=(10, 4))

Page 57 of 72
ML&DA using Python 2024-
2026

[Link](list(k_range), accuracies, 'o-', linewidth=2)


[Link](best_k, color='red', linestyle='--',
label=f'Best K={best_k}')
[Link]('K') ; [Link]('Accuracy')
[Link]('KNN: Accuracy vs K', fontweight='bold')
[Link]() ; [Link](alpha=0.3)
[Link]('ml_p3_knn.png', dpi=150) ; [Link]()

Output

Graph / Plot

Page 58 of 72
ML&DA using Python 2024-
2026

Practical 34: K-Means Clustering

Aim: Apply K-Means Clustering, determine optimal K using Elbow


Method, and visualize clusters.

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: WCSS vs 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](figsize=(8, 4))
[Link](range(1,11), inertias, 'o-', linewidth=2)
[Link](4, color='red', linestyle='--', label='Optimal
K=4')
[Link]('K') ; [Link]('WCSS (Inertia)')
[Link]('Elbow Method', fontweight='bold')
[Link]() ; [Link](alpha=0.3)
[Link]('ml_p4_kmeans.png', dpi=150) ; [Link]()

# Apply K-Means with K=4


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

Page 59 of 72
ML&DA using Python 2024-
2026

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

Output

Graph / Plot

Page 60 of 72
ML&DA using Python 2024-
2026

Practical 35: Support Vector Machine (SVM)

Aim: Implement SVM classifier with RBF kernel, analyze effect of C


on accuracy, and evaluate performance.

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 (critical 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_)

# Plot accuracy vs C
C_values = [0.01,0.1,1,10,100]
accs = []
for c in C_values:

Page 61 of 72
ML&DA using Python 2024-
2026

m = SVC(kernel='rbf',C=c).fit(X_train_s, y_train)
[Link](accuracy_score(y_test, [Link](X_test_s)))
[Link](C_values, accs, 'o-', linewidth=2)
[Link]('SVM: Accuracy vs C (RBF kernel)',
fontweight='bold')
[Link]('C') ; [Link]('Accuracy') ;
[Link](alpha=0.3)
[Link]('ml_p5_svm.png', dpi=150) ; [Link]()

Output

Graph / Plot

Page 62 of 72
ML&DA using Python 2024-
2026

Practical 36: Principal Component Analysis (PCA)

Aim: Apply PCA for dimensionality reduction on the Iris dataset,


visualize explained variance, and project 4D data to 2D.

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 4-feature Iris dataset


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

# PCA: 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 2D for visualization


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

# Plot 2D projection
[Link](figsize=(10, 4))
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],

Page 63 of 72
ML&DA using Python 2024-
2026

label=name, s=50)
[Link]('PC1') ; [Link]('PC2')
[Link]('PCA: 2D Projection of Iris (95.81% variance
retained)',
fontweight='bold')
[Link]() ; [Link](alpha=0.3)
[Link]('ml_p6_pca.png', dpi=150) ; [Link]()

Output

Graph / Plot

Page 64 of 72
ML&DA using Python 2024-
2026

Practical 37: Decision Tree Classifier

Aim: Build a Decision Tree, find optimal depth to prevent


overfitting, and evaluate performance.

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)

Page 65 of 72
ML&DA using Python 2024-
2026

y_pred = [Link](X_test)
print('Accuracy:', accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))

# Accuracy vs Depth plot


[Link](figsize=(10, 4))
[Link](list(depths), train_acc, 'b-o', label='Train
Accuracy')
[Link](list(depths), test_acc, 'r-o', label='Test
Accuracy')
[Link](best_depth, linestyle='--',
label=f'Best={best_depth}')
[Link]('Max Depth') ; [Link]('Accuracy')
[Link]('Decision Tree: Accuracy vs Depth',
fontweight='bold')
[Link]() ; [Link](alpha=0.3)
[Link]('ml_p7_decision_tree.png', dpi=150) ; [Link]()

Output

Graph / Plot

Page 66 of 72
ML&DA using Python 2024-
2026

Page 67 of 72
ML&DA using Python 2024-
2026

Practical 38: Random Forest Classifier

Aim: Implement Random Forest using ensemble learning, analyze effect


of number of trees, compute feature importance.

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)

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

# Plot accuracy vs n_trees

Page 68 of 72
ML&DA using Python 2024-
2026

[Link](figsize=(10, 4))
[Link](n_vals, accs, 'o-', linewidth=2, color='green')
[Link]('Number of Trees') ; [Link]('Accuracy')
[Link]('Random Forest: Accuracy vs # Trees',
fontweight='bold')
[Link](alpha=0.3)
[Link]('ml_p8_random_forest.png', dpi=150) ; [Link]()

Output

Graph / Plot

Page 69 of 72
ML&DA using Python 2024-
2026

Practical 39: Compare All ML Techniques

Aim: Compare all implemented ML algorithms on the same dataset and


visualize results using bar and line charts.

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)
Xs_train = StandardScaler().fit_transform(X_train)
Xs_test = StandardScaler().fit_transform(X_test)

# Train all models


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,

Page 70 of 72
ML&DA using Python 2024-
2026

[Link](X_test))
svm = SVC(kernel='rbf',C=1).fit(Xs_train, y_train)
results['SVM (RBF)'] = accuracy_score(y_test,
[Link](Xs_test))
dt =
DecisionTreeClassifier(max_depth=5,random_state=42).fit(X_tr
ain, 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 sorted results


print('===== ML Algorithms Comparison =====')
for name,acc in sorted([Link](), key=lambda x: -
x[1]):
print(f'{name:20s}: {acc:.4f}')

# Bar + Line chart comparison


fig, (ax1,ax2) = [Link](1, 2, figsize=(12, 5))
colors =
['#4472C4','#ED7D31','#A9D18E','red','#FFC000','#70AD47']
[Link]([Link](), [Link](), color=colors,
edgecolor='black')
ax1.set_ylim(0, 1.1) ; ax1.set_title('Accuracy – Bar Chart',
fontweight='bold')
[Link](list([Link]()), list([Link]()), 'o-',
linewidth=2, color='steelblue', markersize=10,
markerfacecolor='red')
ax2.set_title('Accuracy Trend – Line Chart',
fontweight='bold')
[Link](rotation=15) ; plt.tight_layout()
[Link]('ml_p9_comparison.png', dpi=150) ; [Link]()

Output

Page 71 of 72
ML&DA using Python 2024-
2026

Graph / Plot

Page 72 of 72

You might also like