0% found this document useful (0 votes)
12 views38 pages

Python Programming Lab Exercises

The document outlines a list of Python programming laboratory exercises for the Department of Computer Science at Dr. Lankapalli Bullayya College, covering various topics such as lists, dictionaries, searching algorithms, data handling, statistical calculations, and data manipulation using libraries like NumPy and Pandas. Each exercise includes specific programming tasks and examples demonstrating the implementation of Python features and libraries. The document serves as a comprehensive guide for students to develop their Python programming skills.

Uploaded by

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

Python Programming Lab Exercises

The document outlines a list of Python programming laboratory exercises for the Department of Computer Science at Dr. Lankapalli Bullayya College, covering various topics such as lists, dictionaries, searching algorithms, data handling, statistical calculations, and data manipulation using libraries like NumPy and Pandas. Each exercise includes specific programming tasks and examples demonstrating the implementation of Python features and libraries. The document serves as a comprehensive guide for students to develop their Python programming skills.

Uploaded by

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

Dr. Lankapalli Bullayya College, Visakhapatnam.

Department of Computer Science - PG


Python Programming Laboratory
List of Record Programs

1. Develop a Python Program on Lists


2. Develop a Python Program on Dictionaries
3. Develop a Python Program to perform Search for given number in list of Numbers using linear
search or Binary Search technique
4. Develop a Python Program to sort given number in list of Numbers
5. Develop a Python Program on Text Handling
6. Develop a Python Program for calculating Mean, Mode, Median, Variance, standard deviation
7. Develop a Python Program for Karl Pearson Coefficient of Correlation, Rank Correlation
8. Develop a Python Program on NumPy Arrays
9. Develop a Python Program for Linear Algebra with NumPy
10. Develop a Python Program for creation and manipulation of Data Frames using Pandas Library
11. Develop a Python Program for the following
a. Simple Line Plots
b. Adjusting the Plot: Line Colors and Styles, Axes Limits, Labeling Plots,
c. Simple Scatter Plots
d. Histograms
e. Customizing Plot Legends
f. Choosing Elements for the Legend
g. Boxplot
h. Multiple Legends
i. Customizing Colorbars
j. Multiple Subplots
k. Text and Annotation
l. Customizing Ticks
12. Develop a Python Program for Data preprocessing: Handling missing values, handling
categorical data, bringing features to same scale, selecting meaningful features
13. Develop a Python Program for Compressing data via dimensionality reduction: PCA
14. Develop a Python Program for Data Clustering
15. Develop a Python Program for Classification
16. Develop a Python Program for Model Evaluation: K-fold cross validation
PYTHON RECORD WORK

######## 1. Develop a Python Program on Lists

#Creating and Manipulating Lists

# a. Creating a list
fruits = ['Apple', 'Banana', 'Orange', 'Mango']

# Displaying the original list


print("Original List:")
print(fruits)

# b. Accessing elements in a list


first_fruit = fruits[0]
second_fruit = fruits[1]

# Displaying accessed elements


print("\nAccessing Elements:")
print("First Fruit:", first_fruit)
print("Second Fruit:", second_fruit)

# c. Adding elements to the end of the list


[Link]('Grapes')

# Displaying the list after adding an element


print("\nAfter Adding 'Grapes':")
print(fruits)

# d. Inserting an element at a specific position


[Link](1, 'Kiwi')

# Displaying the list after inserting 'Kiwi'


print("\nAfter Inserting 'Kiwi' at Index 1:")
print(fruits)

# e. Removing an element by value


[Link]('Banana')

# Displaying the list after removing 'Banana'


print("\nAfter Removing 'Banana':")
print(fruits)

# f. Removing an element by index


removed_fruit = [Link](2)

# Displaying the list and the removed element


print("\nAfter Popping at Index 2:")
print("Removed Fruit:", removed_fruit)
print(fruits)

# g. Checking if an element is in the list


is_mango_in_list = 'Mango' in fruits

# Displaying the result


print("\nIs 'Mango' in the List?", is_mango_in_list)
# h. Sorting the list
[Link]()

# Displaying the sorted list


print("\nSorted List:")
print(fruits)

# i. Reversing the list


[Link]()

# Displaying the reversed list


print("\nReversed List:")
print(fruits)

### output:

Original List:
['Apple', 'Banana', 'Orange', 'Mango']

Accessing Elements:
First Fruit: Apple
Second Fruit: Banana

After Adding 'Grapes':


['Apple', 'Banana', 'Orange', 'Mango', 'Grapes']

After Inserting 'Kiwi' at Index 1:


['Apple', 'Kiwi', 'Banana', 'Orange', 'Mango', 'Grapes']

After Removing 'Banana':


['Apple', 'Kiwi', 'Orange', 'Mango', 'Grapes']

After Popping at Index 2:


Removed Fruit: Orange
['Apple', 'Kiwi', 'Mango', 'Grapes']

Is 'Mango' in the List? True

Sorted List:
['Apple', 'Grapes', 'Kiwi', 'Mango']

Reversed List:
['Mango', 'Kiwi', 'Grapes', 'Apple']
####### [Link] a Python Program on Dictionaries

#Developing a Python Program on Dictionaries

# a. Creating and Manipulating Dictionaries

# Creating a dictionary
student_info = {
'name': 'John',
'age': 20,
'grade': 'A',
'courses': ['Math', 'Physics', 'English'] }

# Displaying the original dictionary


print("Original Dictionary:")
print(student_info)

# b. Accessing values in a dictionary


student_name = student_info['name']
student_courses = student_info['courses']

# Displaying accessed values


print("\nAccessing Values:")
print("Student Name:", student_name)
print("Student Courses:", student_courses)

# c. Adding a new key-value pair


student_info['gender'] = 'Male'

# Displaying the dictionary after adding a new key-value pair


print("\nAfter Adding 'gender':")
print(student_info)

# d. Updating the value of an existing key


student_info['age'] = 21

# Displaying the dictionary after updating 'age'


print("\nAfter Updating 'age' to 21:")
print(student_info)

# e. Removing a key-value pair


removed_grade = student_info.pop('grade')

# Displaying the dictionary and the removed value


print("\nAfter Popping 'grade':")
print("Removed Grade:", removed_grade)
print(student_info)

# f. Checking if a key is in the dictionary


has_grade = 'grade' in student_info

# Displaying the result


print("\nDoes the Dictionary Have 'grade' Key?", has_grade)

# g. Getting all keys and values


all_keys = student_info.keys()
all_values = student_info.values()

# Displaying all keys and values


print("\nAll Keys:")
print(all_keys)
print("All Values:")
print(all_values)

# h. Iterating through key-value pairs


print("\nIterating Through Key-Value Pairs:")
for key, value in student_info.items():
print(f"{key}: {value}")

### output:

Original Dictionary:
{'name': 'John', 'age': 20, 'grade': 'A', 'courses': ['Math', 'Physics',
'English']}

Accessing Values:
Student Name: John
Student Courses: ['Math', 'Physics', 'English']

After Adding 'gender':


{'name': 'John', 'age': 20, 'grade': 'A', 'courses': ['Math', 'Physics',
'English'], 'gender': 'Male'}

After Updating 'age' to 21:


{'name': 'John', 'age': 21, 'grade': 'A', 'courses': ['Math', 'Physics',
'English'], 'gender': 'Male'}

After Popping 'grade':


Removed Grade: A
{'name': 'John', 'age': 21, 'courses': ['Math', 'Physics', 'English'],
'gender': 'Male'}

Does the Dictionary Have 'grade' Key? False

All Keys:
dict_keys(['name', 'age', 'courses', 'gender'])
All Values:
dict_values(['John', 21, ['Math', 'Physics', 'English'], 'Male'])

Iterating Through Key-Value Pairs:


name: John
age: 21
courses: ['Math', 'Physics', 'English']
gender: Male
####### 3. Develop a Python Program to perform Search for given number in
list of Numbers ####### using linear
####### search or Binary Search technique

#Python Program for Linear Search and Binary Search

# Linear Search
def linear_search(numbers, target):
for i, num in enumerate(numbers):
if num == target:
return i # Return the index if the target is found
return -1 # Return -1 if the target is not found

# Binary Search (Assumes the list is sorted)


def binary_search(numbers, target):
low, high = 0, len(numbers) - 1

while low <= high:


mid = (low + high) // 2
mid_value = numbers[mid]

if mid_value == target:
return mid # Return the index if the target is found
elif mid_value < target:
low = mid + 1
else:
high = mid - 1

return -1 # Return -1 if the target is not found

# Input data
numbers = [2, 5, 8, 12, 16, 23, 38, 42, 56, 72, 91]
target_number = 23

# Perform Linear Search


linear_search_result = linear_search(numbers, target_number)

# Display Linear Search Result


if linear_search_result != -1:
print(f"Linear Search: {target_number} found at index
{linear_search_result}")
else:
print(f"Linear Search: {target_number} not found in the list")

# Perform Binary Search (List must be sorted)


[Link]()
binary_search_result = binary_search(numbers, target_number)

# Display Binary Search Result


if binary_search_result != -1:
print(f"Binary Search: {target_number} found at index
{binary_search_result}")
else:
print(f"Binary Search: {target_number} not found in the list")
### output:

Linear Search: 23 found at index 5


Binary Search: 23 found at index 7

###### 4. Develop a Python Program to sort given number in list of


Numbers

#Python Program for Sorting a List of Numbers

# Input data
numbers = [8, 3, 1, 7, 5, 10, 2, 6, 4, 9]

# Using sorted() function to sort the list


sorted_numbers = sorted(numbers)

# Displaying the original and sorted lists


print("Original List:", numbers)
print("Sorted List:", sorted_numbers)

### output:
Original List: [8, 3, 1, 7, 5, 10, 2, 6, 4, 9]
Sorted List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

(or)

# Using sort() method to sort the list in-place


[Link]()

# Displaying the sorted list in-place


print("Sorted List (In-place):", numbers)
######## 5. Develop a Python Program on Text Handling

def process_text(input_file, output_file):


"""
Read text from an input file, process it, and write the result to an
output file.

Parameters:
- input_file: The path to the input text file.
- output_file: The path to the output text file.

Returns:
- None
"""
try:
# Read text from the input file
with open(input_file, 'r') as file:
text_content = [Link]()

# Process the text (convert to uppercase in this example)


processed_text = text_content.upper()

# Write the processed text to the output file


with open(output_file, 'w') as file:
[Link](processed_text)

print("Text processing successful. Result written to",


output_file)

except FileNotFoundError:
print("Error: File not found.")
except Exception as e:
print("An error occurred:", str(e))

def main():
# Example usage
input_file_path = "[Link]"
output_file_path = "[Link]"

# Create an example input file


with open(input_file_path, 'w') as file:
[Link]("Hello, this is an example text for processing.")

# Process the text and write the result to an output file


process_text(input_file_path, output_file_path)

if __name__ == "__main__":
main()

### output:(will be open in a new (output)file in our local system)

#HELLO, THIS IS AN EXAMPLE TEXT FOR PROCESSING.


###### 6. Develop a Python Program for calculating Mean, Mode, Median,
###### Variance, standard deviation

#Python Program for Calculating Mean, Mode, Median, Variance, and


Standard #Deviation

from statistics import mean, mode, median, variance, stdev

# Input data
numbers = [8, 3, 1, 7, 5, 10, 2, 6, 4, 9]

# Calculate mean
mean_value = mean(numbers)

# Calculate mode
mode_value = mode(numbers)

# Calculate median
median_value = median(numbers)

# Calculate variance
variance_value = variance(numbers)

# Calculate standard deviation


stdev_value = stdev(numbers)

# Displaying the calculated statistics


print("Original List:", numbers)
print("Mean:", mean_value)
print("Mode:", mode_value)
print("Median:", median_value)
print("Variance:", variance_value)
print("Standard Deviation:", stdev_value)

### output:

Original List: [8, 3, 1, 7, 5, 10, 2, 6, 4, 9]


Mean: 5.5
Mode: 1
Median: 5.5
Variance: 8.25
Standard Deviation: 2.8722813232690143
######## 7. Develop a Python Program for Karl Pearson Coefficient of
Correlation, Rank ######## Correlation

### Correlation

def karl_pearson_correlation(x, y):


n = len(x)
mean_x = sum(x) / n
mean_y = sum(y) / n
numerator = sum((x[i] - mean_x) * (y[i] - mean_y) for i in range(n))
denominator_x = sum((x[i] - mean_x)**2 for i in range(n))
denominator_y = sum((y[i] - mean_y)**2 for i in range(n))
correlation_coefficient = numerator / (denominator_x**0.5 *
denominator_y**0.5)
return correlation_coefficient

# Example usage
x_values = [2, 4, 6, 8, 10]
y_values = [1, 2, 3, 4, 5]

pearson_coefficient = karl_pearson_correlation(x_values, y_values)


print("Karl Pearson Coefficient of Correlation:", pearson_coefficient)

### output:
Karl Pearson Coefficient of Correlation: 1.0

### spearman correlation

def spearman_rank_correlation(x, y):


n = len(x)
rank_x = [sorted(x).index(xi) + 1 for xi in x]
rank_y = [sorted(y).index(yi) + 1 for yi in y]
d = [rank_x[i] - rank_y[i] for i in range(n)]
correlation_coefficient = 1 - (6 * sum(d**2) / (n * (n**2 - 1)))
return correlation_coefficient

# Example usage
x_values = [2, 4, 6, 8, 10]
y_values = [1, 2, 3, 4, 5]

spearman_coefficient = spearman_rank_correlation(x_values, y_values)


print("Spearman's Rank Correlation:", spearman_coefficient)

### output:
Spearman's Rank Correlation: 1.0
######## 8. Develop a Python Program on NumPy Arrays

### numpy array programe

import numpy as np

def numpy_array_operations():
# Creating NumPy arrays
array1 = [Link]([1, 2, 3, 4, 5])
array2 = [Link]([5, 4, 3, 2, 1])

# Performing basic operations


sum_result = array1 + array2
product_result = array1 * array2
dot_product_result = [Link](array1, array2)

# Displaying the original arrays and results


print("Array 1:", array1)
print("Array 2:", array2)
print("Sum of arrays:", sum_result)
print("Product of arrays:", product_result)
print("Dot product of arrays:", dot_product_result)

# Reshaping arrays
reshaped_array1 = [Link]((5, 1))
reshaped_array2 = [Link]((1, 5))

# Performing operations on reshaped arrays


outer_product_result = [Link](reshaped_array1, reshaped_array2)

# Displaying the reshaped arrays and result


print("\nReshaped Array 1:")
print(reshaped_array1)
print("\nReshaped Array 2:")
print(reshaped_array2)
print("\nOuter product of reshaped arrays:")
print(outer_product_result)

if __name__ == "__main__":
numpy_array_operations()

### output:

Array 1: [1 2 3 4 5]
Array 2: [5 4 3 2 1]
Sum of arrays: [6 6 6 6 6]
Product of arrays: [5 8 9 8 5]
Dot product of arrays: 35

Reshaped Array 1:
[[1]
[2]
[3]
[4]
[5]]
Reshaped Array 2:
[[5 4 3 2 1]]

Outer product of reshaped arrays:


[[ 5 4 3 2 1]
[10 8 6 4 2]
[15 12 9 6 3]
[20 16 12 8 4] [25 20 15 10 5]]
###### 9. Develop a Python Program for Linear Algebra with NumPy

### numpy algebra

import numpy as np

def linear_algebra_operations():
# Creating NumPy matrices
matrix_a = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix_b = [Link]([[9, 8, 7], [6, 5, 4], [3, 2, 1]])

# Displaying the original matrices


print("Matrix A:")
print(matrix_a)
print("\nMatrix B:")
print(matrix_b)

# Matrix addition
sum_matrix = [Link](matrix_a, matrix_b)

# Matrix multiplication
product_matrix = [Link](matrix_a, matrix_b)

# Matrix transpose
transpose_matrix_a = [Link](matrix_a)
transpose_matrix_b = [Link](matrix_b)

# Displaying the results


print("\nSum of matrices A and B:")
print(sum_matrix)
print("\nProduct of matrices A and B:")
print(product_matrix)
print("\nTranspose of matrix A:")
print(transpose_matrix_a)
print("\nTranspose of matrix B:")
print(transpose_matrix_b)

if __name__ == "__main__":
linear_algebra_operations()

### output:

Matrix A:
[[1 2 3]
[4 5 6]
[7 8 9]]

Matrix B:
[[9 8 7]
[6 5 4]
[3 2 1]]

Sum of matrices A and B:


[[10 10 10]
[10 10 10][10 10 10]]

Product of matrices A and B:


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

Transpose of matrix A:
[[1 4 7]
[2 5 8]
[3 6 9]]

Transpose of matrix B:
[[9 6 3]
[8 5 2]
[7 4 1]]
######## [Link] a Python Program for creation and manipulation of
Data Frames ######## using Pandas Library

import pandas as pd

def create_and_manipulate_dataframe():
# Creating a DataFrame from a dictionary
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
'Age': [25, 30, 22, 35, 28],
'City': ['New York', 'San Francisco', 'Los Angeles', 'Chicago',
'Miami']
}

df = [Link](data)

# Displaying the original DataFrame


print("Original DataFrame:")
print(df)

# Adding a new column


df['Occupation'] = ['Engineer', 'Doctor', 'Artist', 'Teacher',
'Designer']

# Displaying the DataFrame after adding a new column


print("\nDataFrame after adding the 'Occupation' column:")
print(df)

# Filtering data based on a condition


filtered_df = df[df['Age'] > 25]

# Displaying the DataFrame after filtering


print("\nDataFrame after filtering for individuals older than 25:")
print(filtered_df)

# Sorting the DataFrame by age in descending order


sorted_df = df.sort_values(by='Age', ascending=False)

# Displaying the DataFrame after sorting


print("\nDataFrame after sorting by age in descending order:")
print(sorted_df)

if __name__ == "__main__":
create_and_manipulate_dataframe()

### output:

Original DataFrame:

Name Age City


0 Alice 25 New York
1 Bob 30 San Francisco
2 Charlie 22 Los Angeles
3 David 35 Chicago
4 Eva 28 Miami
DataFrame after adding the 'Occupation' column:

Name Age City Occupation


0 Alice 25 New York Engineer
1 Bob 30 San Francisco Doctor
2 Charlie 22 Los Angeles Artist
3 David 35 Chicago Teacher
4 Eva 28 Miami Designer

DataFrame after filtering for individuals older than 25:


Name Age City Occupation
1 Bob 30 Doctor
3 David 35 Teacher
4 Eva 28 Designer

DataFrame after sorting by age in descending order:


Name Age City Occupation
3 David 35 Chicago Teacher
1 Bob 30 San Francisco Doctor
4 Eva 28 Miami Designer
0 Alice 25 New York Engineer
2 Charlie 22 Los Angeles Artist
####### [Link] a Python Program for the following
#a. Simple Line Plots
#b. Adjusting the Plot: Line Colors and Styles, Axes Limits,
Labeling Plots,
#c. Simple Scatter Plots
#d. Histograms
#e. Customizing Plot Legends
#f. Choosing Elements for the Legend
#g. Boxplot
#h. Multiple Legends
#i. Customizing Colorbars
#j. Multiple Subplots
#k. Text and Annotation
#l. Customizing Ticks

import numpy as np
import [Link] as plt
import seaborn as sns

# Set the style for better visualization


[Link](style="whitegrid")

# a. Simple Line Plots


def simple_line_plot():
x = [Link](0, 10, 100)
y = [Link](x)

[Link](figsize=(8, 4))
[Link](x, y, label='sin(x)')
[Link]('Simple Line Plot')
[Link]('x')
[Link]('y')
[Link]()
[Link]()

simple_line_plot()

OUTPUT:
# b. Adjusting the Plot: Line Colors and Styles, Axes Limits, Labeling
Plots

import numpy as np
import [Link] as plt
import seaborn as sns

# Set the style for better visualization


[Link](style="whitegrid")
def adjusting_plot():
x = [Link](0, 10, 100)
y1 = [Link](x)
y2 = [Link](x)

[Link](figsize=(8, 4))
[Link](x, y1, 'r--', label='sin(x)')
[Link](x, y2, 'b-', label='cos(x)')
[Link]('Adjusted Line Plot')
[Link]('x')
[Link]('y')
[Link](-1.5, 1.5)
[Link]()
[Link]()
adjusting_plot()

OUTPUT:
# c. Simple Scatter Plots

import numpy as np
import [Link] as plt
import seaborn as sns

# Set the style for better visualization


[Link](style="whitegrid")
def simple_scatter_plot():
x = [Link](50)
y = [Link](50)

[Link](figsize=(8, 4))
[Link](x, y, color='blue', marker='o', label='Random Points')
[Link]('Simple Scatter Plot')
[Link]('X')
[Link]('Y')
[Link]()
[Link]()
simple_scatter_plot()

OUTPUT:
# d. Histograms

import numpy as np
import [Link] as plt
import seaborn as sns

# Set the style for better visualization


[Link](style="whitegrid")
def histograms():
data = [Link](1000)

[Link](figsize=(8, 4))
[Link](data, bins=30, alpha=0.7, color='green', edgecolor='black')
[Link]('Histogram')
[Link]('Value')
[Link]('Frequency')
[Link]()

histograms()
OUTPUT:
# e. Customizing Plot Legends

import numpy as np
import [Link] as plt
import seaborn as sns

# Set the style for better visualization


[Link](style="whitegrid")
def customizing_legends():
x = [Link](0, 10, 100)
y1 = [Link](x)
y2 = [Link](x)

[Link](figsize=(8, 4))
[Link](x, y1, 'r--', label='sin(x)')
[Link](x, y2, 'b-', label='cos(x)')
[Link]('Customized Legends')
[Link]('x')
[Link]('y')
[Link](loc='upper right', fontsize='small')
[Link]()
customizing_legends()

OUTPUT:
# f. Choosing Elements for the Legend

import numpy as np
import [Link] as plt
import seaborn as sns

# Set the style for better visualization


[Link](style="whitegrid")
def choosing_elements_for_legend():
x = [Link](0, 10, 100)
y1 = [Link](x)
y2 = [Link](x)

[Link](figsize=(8, 4))
line1, = [Link](x, y1, 'r--', label='sin(x)')
line2, = [Link](x, y2, 'b-', label='cos(x)')
[Link]('Choosing Elements for Legend')
[Link]('x')
[Link]('y')
[Link](handles=[line1, line2], loc='upper right',
fontsize='small')
[Link]()
choosing_elements_for_legend()

OUTPUT:
# g. Boxplot

import numpy as np
import [Link] as plt
import seaborn as sns

# Set the style for better visualization


[Link](style="whitegrid")

def boxplot():
data = [[Link](0, std, 100) for std in range(1, 4)]

[Link](figsize=(8, 4))
[Link](data, vert=True, patch_artist=True)
[Link]('Boxplot')
[Link]('Category')
[Link]('Value')
[Link]()
boxplot()

OUTPUT:
# h. Multiple Legends

import numpy as np
import [Link] as plt
import seaborn as sns

# Set the style for better visualization


[Link](style="whitegrid")

def multiple_legends():
x = [Link](0, 10, 100)
y1 = [Link](x)
y2 = [Link](x)

[Link](figsize=(8, 4))
[Link](x, y1, 'r--', label='sin(x)')
[Link](x, y2, 'b-', label='cos(x)')
[Link]('Multiple Legends')
[Link]('x')
[Link]('y')

[Link](loc='upper right', fontsize='small')


[Link](loc='lower right', fontsize='small')

[Link]()
multiple_legends()

OUTPUT:
# i. Customizing Colorbars

import numpy as np
import [Link] as plt
import seaborn as sns

# Set the style for better visualization


[Link](style="whitegrid")

def customizing_colorbars():
x = [Link](0, 10, 100)
y = [Link](0, 10, 100)
z = [Link](x) + [Link](y)

[Link](figsize=(8, 4))
scatter = [Link](x, y, c=z, cmap='viridis', s=30, alpha=0.8)
[Link](scatter, label='z = sin(x) + cos(y)')
[Link]('Customizing Colorbars')
[Link]('x')
[Link]('y')
[Link]()
customizing_colorbars()

OUTPUT:
# j. Multiple Subplots

import numpy as np
import [Link] as plt
import seaborn as sns

# Set the style for better visualization


[Link](style="whitegrid")

def multiple_subplots():
x = [Link](0, 10, 100)
y1 = [Link](x)
y2 = [Link](x)

fig, axes = [Link](nrows=2, ncols=1, figsize=(8, 6))

axes[0].plot(x, y1, 'r--', label='sin(x)')


axes[0].set_title('Subplot 1')
axes[0].legend()

axes[1].plot(x, y2, 'b-', label='cos(x)')


axes[1].set_title('Subplot 2')
axes[1].legend()

plt.tight_layout()
[Link]()
multiple_subplots()

OUTPUT:
# k. Text and Annotation

import numpy as np
import [Link] as plt
import seaborn as sns

# Set the style for better visualization


[Link](style="whitegrid")

def text_and_annotation():
x = [Link](0, 10, 100)
y = [Link](x)

[Link](figsize=(8, 4))
[Link](x, y, 'r--', label='sin(x)')
[Link]('Text and Annotation')
[Link]('x')
[Link]('y')

[Link](2, 0.8, 'Max Value', fontsize=10, color='blue')


[Link]('Local Minimum', xy=(5, -0.5), xytext=(7, -0.8),
arrowprops=dict(facecolor='black', shrink=0.05))

[Link]()
[Link]()
text_and_annotation()

OUTPUT:
# l. Customizing Ticks

import numpy as np
import [Link] as plt
import seaborn as sns

# Set the style for better visualization


[Link](style="whitegrid")

def customizing_ticks():
x = [Link](0, 10, 100)
y = [Link](x)

[Link](figsize=(8, 4))
[Link](x, y, 'r--', label='sin(x)')
[Link]('Customizing Ticks')
[Link]('x')
[Link]('y')

[Link]([Link](0, 11, 2)) # Customizing x-axis ticks


[Link]([Link](-1, 1.5, 0.5)) # Customizing y-axis ticks

[Link]()
[Link]()
customizing_ticks()

OUTPUT:
### [Link] a Python Program for Data preprocessing: Handling missing
values, handling
### categorical data, bringing features to same scale, selecting
meaningful feature

import pandas as pd
from [Link] import SimpleImputer
from [Link] import StandardScaler, OneHotEncoder
from [Link] import ColumnTransformer
from [Link] import Pipeline
from [Link] import RandomForestClassifier
from sklearn.model_selection import train_test_split
from [Link] import accuracy_score

# Function to load a sample dataset (you can replace it with your


dataset)
def load_dataset():
data = {
'Age': [25, 30, None, 35, 28],
'Gender': ['Male', 'Female', 'Male', 'Female', 'Male'],
'Salary': [50000, 60000, None, 75000, 70000],
'Outcome': ['Yes', 'No', 'No', 'Yes', 'No']
}
df = [Link](data)
return df

# Function for data preprocessing


def data_preprocessing(df):
# Splitting data into features and target
X = [Link]('Outcome', axis=1)
y = df['Outcome']

# Splitting data into training and testing sets


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

# Creating a transformer for numerical features


numerical_features =
X_train.select_dtypes(include=['number']).columns
numerical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='mean')),
('scaler', StandardScaler())
])

# Creating a transformer for categorical features


categorical_features =
X_train.select_dtypes(include=['object']).columns
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='most_frequent')),
('onehot', OneHotEncoder(handle_unknown='ignore'))
])

# Combining transformers using ColumnTransformer


preprocessor = ColumnTransformer(
transformers=[
('num', numerical_transformer, numerical_features),
('cat', categorical_transformer, categorical_features)
])

# Creating a pipeline with preprocessing and a simple model


model = Pipeline(steps=[
('preprocessor', preprocessor),
('classifier', RandomForestClassifier(random_state=42))
])

# Training the model


[Link](X_train, y_train)

# Making predictions
y_pred = [Link](X_test)

# Evaluating the model


accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)

if __name__ == "__main__":
# Load the dataset
df = load_dataset()

# Display the original dataset


print("Original Dataset:")
print(df)

# Perform data preprocessing


print("\nData Preprocessing and Model Evaluation:")
data_preprocessing(df)

### output:

Original Dataset:
Age Gender Salary Outcome
0 25.0 Male 50000.0 Yes
1 30.0 Female 60000.0 No
2 NaN Male NaN No
3 35.0 Female 75000.0 Yes
4 28.0 Male 70000.0 No

Data Preprocessing and Model Evaluation:


Accuracy: 1.0
######## [Link] a Python Program for Compressing data via
dimensionality reduction: PCA

import numpy as np
import pandas as pd
from [Link] import PCA
from [Link] import load_iris
import [Link] as plt

def compress_data_with_pca():
# Load a sample dataset (you can replace it with your own dataset)
iris = load_iris()
X = [Link]
y = [Link]

# Apply PCA to compress data to 2 dimensions


pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)

# Create a DataFrame for visualization


df_pca = [Link](data=X_pca, columns=['Principal Component 1',
'Principal Component 2'])
df_pca['Target'] = y

# Display the original dataset


print("Original Dataset:")
print([Link](data=X, columns=iris.feature_names).head())

# Display the compressed dataset


print("\nCompressed Dataset after PCA:")
print(df_pca.head())

# Visualize the compressed data


[Link](figsize=(8, 6))
targets = set(y)
colors = ['r', 'g', 'b']
for target, color in zip(targets, colors):
indices_to_keep = df_pca['Target'] == target
[Link](df_pca.loc[indices_to_keep, 'Principal Component 1'],
df_pca.loc[indices_to_keep, 'Principal Component 2'],
c=color, label=target)
[Link]('Principal Component 1')
[Link]('Principal Component 2')
[Link]('PCA: Compressed Data Visualization')
[Link]()
[Link]()

if __name__ == "__main__":
compress_data_with_pca()
### output:

Original Dataset:
sepal length (cm) sepal width (cm) petal length (cm) petal width
(cm)
0 5.1 3.5 1.4
0.2
1 4.9 3.0 1.4
0.2
2 4.7 3.2 1.3
0.2
3 4.6 3.1 1.5
0.2
4 5.0 3.6 1.4
0.2

Compressed Dataset after PCA:


Principal Component 1 Principal Component 2 Target
0 -2.684126 0.319397 0
1 -2.714142 -0.177001 0
2 -2.888991 -0.144949 0
3 -2.745343 -0.318299 0
4 -2.728717 0.326755 0

OUTPUT:
############ [Link] a Python Program for Data Clustering.

import numpy as np
import pandas as pd
from [Link] import KMeans
from [Link] import make_blobs
import [Link] as plt

def perform_kmeans_clustering():
# Generate a sample dataset with three clusters
X, y = make_blobs(n_samples=300, centers=3, random_state=42,
cluster_std=1.0)

# Apply K-Means clustering


kmeans = KMeans(n_clusters=3, random_state=42)
[Link](X)

# Add cluster labels to the dataset


labels = kmeans.labels_
clustered_data = [Link](data=np.c_[X, labels],
columns=['Feature 1', 'Feature 2', 'Cluster'])

# Display the original dataset


print("Original Dataset:")
print([Link](data=X, columns=['Feature 1', 'Feature
2']).head())

# Display the clustered dataset


print("\nClustered Dataset:")
print(clustered_data.head())

# Visualize the clustered data


[Link](figsize=(8, 6))
[Link](X[:, 0], X[:, 1], c=labels, cmap='viridis',
edgecolor='k')
centers = kmeans.cluster_centers_
[Link](centers[:, 0], centers[:, 1], c='red', marker='X', s=200,
label='Cluster Centers')
[Link]('K-Means Clustering')
[Link]('Feature 1')
[Link]('Feature 2')
[Link]()
[Link]()

if __name__ == "__main__":
perform_kmeans_clustering()
### output:

Original Dataset:
Feature 1 Feature 2
0 -7.338988 -7.729954
1 -7.740041 -7.264665
2 -1.686653 7.793442
3 4.422198 3.071947
4 -8.917752 -7.888196

Clustered Dataset:
Feature 1 Feature 2 Cluster
0 -7.338988 -7.729954 1.0
1 -7.740041 -7.264665 1.0
2 -1.686653 7.793442 0.0
3 4.422198 3.071947 2.0
4 -8.917752 -7.888196 1.0

OUTPUT:
######### [Link] a Python Program for Classification.

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from [Link] import DecisionTreeClassifier
from [Link] import accuracy_score, classification_report
from [Link] import load_iris

def perform_classification():
# Load the Iris dataset (you can replace it with your own dataset)
iris = load_iris()
X = [Link]
y = [Link]

# Split the dataset into training and testing sets


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

# Create a Decision Tree classifier


classifier = DecisionTreeClassifier(random_state=42)

# Train the classifier on the training data


[Link](X_train, y_train)

# Make predictions on the test data


y_pred = [Link](X_test)

# Evaluate the classifier


accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred)

# Display the results


print("Accuracy:", accuracy)
print("\nClassification Report:")
print(report)

if __name__ == "__main__":
perform_classification()
### output:

Classification Report:
precision recall f1-score support

0 1.00 1.00 1.00 10


1 1.00 1.00 1.00 9
2 1.00 1.00 1.00 11

accuracy 1.00 30
macro avg 1.00 1.00 1.00 30
weighted avg 1.00 1.00 1.00 30
######## [Link] a Python Program for Model Evaluation: K-fold cross
validation.

import numpy as np
from sklearn.model_selection import KFold, cross_val_score
from [Link] import DecisionTreeClassifier
from [Link] import load_iris

def perform_kfold_cross_validation():
# Load the Iris dataset (you can replace it with your own dataset)
iris = load_iris()
X = [Link]
y = [Link]

# Create a Decision Tree classifier


classifier = DecisionTreeClassifier(random_state=42)

# Specify the number of folds for cross-validation


num_folds = 5

# Create a KFold object


kfold = KFold(n_splits=num_folds, shuffle=True, random_state=42)

# Perform K-fold cross-validation and evaluate the model


scores = cross_val_score(classifier, X, y, cv=kfold,
scoring='accuracy')

# Display the cross-validation results


print("Cross-Validation Results:")
for fold, score in enumerate(scores, start=1):
print(f"Fold {fold}: Accuracy = {score:.4f}")

# Calculate and display the mean accuracy


mean_accuracy = [Link](scores)
print(f"\nMean Accuracy across {num_folds} folds:
{mean_accuracy:.4f}")

if __name__ == "__main__":
perform_kfold_cross_validation()

### Output:
Cross-Validation Results:
Fold 1: Accuracy = 1.0000
Fold 2: Accuracy = 0.9667
Fold 3: Accuracy = 0.9333
Fold 4: Accuracy = 0.9333
Fold 5: Accuracy = 0.9333

Mean Accuracy across 5 folds: 0.9533

You might also like