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

Python Lab Manual

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

Python Lab Manual

python -matpolib scikit learn advanced lab
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

Experiment 1: Sorting Three Integers Using min() and max()

Problem Statement:
Create a Python program that reads three integers from the user and displays them in
sorted order (from smallest to largest). The program uses the min() and max() functions to
identify the smallest and largest values. The middle value is calculated by subtracting the
minimum and maximum values from the sum of all three integers.

Analysis of the Problem:


The program requires logical analysis to determine the order of three integers without
using built-in sorting methods. By applying min() and max() functions, the smallest and
largest values are easily identified. The remaining value is obtained through arithmetic
calculation. This improves logical thinking and avoids complexity.

Algorithm:
1. Start
2. Declare three integer variables
3. Read three integers from the user
4. Find the smallest value using min()
5. Find the largest value using max()
6. Calculate the middle value using sum − (min + max)
7. Arrange the values in ascending order
8. Display the sorted result
9. Verify the output
10. Stop

Procedure:
1. Start the system and ensure Python is properly installed.
2. Open a Python development environment such as IDLE, VS Code, or PyCharm.
3. Create a new Python file and name it appropriately (e.g., sort_three_numbers.py).
4. Declare three integer variables to store user input values.
5. Use the input() function to read three integers from the user.
6. Apply the min() function to determine the smallest value among the inputs.
7. Apply the max() function to determine the largest value among the inputs.
8. Compute the middle value by subtracting the smallest and largest values from the sum of
all three numbers.
9. Display the numbers in ascending (sorted) order using the print() function.
10. Execute the program, verify the output, and record the result.
Program:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

smallest = min(a, b, c)
largest = max(a, b, c)
middle = (a + b + c) - (smallest + largest)

print("Numbers in sorted order:")


print(smallest, middle, largest)

Output:
---------------------------------
Enter first number: 8
Enter second number: 3
Enter third number: 5

Numbers in sorted order:


3 5 8
---------------------------------

Conclusion:
Thus, the Python program was successfully executed to sort three integers in ascending
order using the min() and max() functions, and the output was verified.
Experiment 2: Vowel or Consonant Identification

Problem Statement:
Create a Python program that reads a single letter of the English alphabet from the user. If
the user enters any one of the vowels namely a, e, i, o, or u, the program should display a
message indicating that the entered letter is a vowel. If the user enters the letter y, the
program should display a message stating that sometimes y is a vowel and sometimes it is a
consonant. For any other alphabet, the program should display a message indicating that
the entered letter is a consonant.

Analysis of the Problem:


This problem focuses on identifying the nature of a character entered by the user. The
program must first read a single alphabet character and convert it to lowercase to ensure
uniform comparison. Using conditional statements, the program checks whether the
character belongs to the set of vowels. A special condition is handled for the letter 'y', as it
does not always behave strictly as a vowel or a consonant. All remaining letters are
classified as consonants. This approach strengthens the understanding of conditional logic
and character comparison in Python.

Algorithm:
1. Start
2. Read a character from the user
3. Convert the character to lowercase
4. Check if the character is one of the vowels (a, e, i, o, u)
5. If true, display that the letter is a vowel
6. Else if the character is 'y'
7. Display that 'y' is sometimes a vowel and sometimes a consonant
8. Else display that the letter is a consonant
9. Verify the result
10. Stop

Procedure:
1. Switch on the computer system and ensure Python is properly installed.
2. Open a Python development environment such as IDLE or Visual Studio Code.
3. Create a new Python file and name it appropriately (e.g., vowel_consonant.py).
4. Write Python code to read a single character using the input() function.
5. Convert the entered character into lowercase to avoid case sensitivity.
6. Use conditional statements to compare the input character with vowel letters.
7. Include a separate condition to handle the special case of the letter 'y'.
8. Print appropriate messages based on the condition satisfied.
9. Execute the program and provide different inputs to test all cases.
10. Observe and record the output obtained.

Program:
# Program to check whether a letter is a vowel or a consonant

# Reading input from the user


letter = input("Enter a letter of the alphabet: ")

# Converting input to lowercase to handle uppercase letters


letter = [Link]()

# Checking if the input is a single alphabet character


if [Link]() and len(letter) == 1:

# Checking for vowels


if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
print("The entered letter is a vowel.")

# Special case for 'y'


elif letter == 'y':
print("The entered letter 'y' is sometimes a vowel and sometimes a consonant.")

# All other letters are consonants


else:
print("The entered letter is a consonant.")
else:
print("Invalid input. Please enter a single alphabet letter.")

Output:
---------------------------------
Enter a letter of the alphabet: y
The entered letter 'y' is sometimes a vowel and sometimes a consonant.
---------------------------------

Conclusion:
Thus, the Python program was successfully executed to determine whether the entered
letter is a vowel, a consonant, or the special case letter 'y', and the output was verified.
Experiment 3: Random Password Generator Using ASCII Values

Problem Statement:
Write a Python function that generates a random password. The password should have a
random length between 7 and 10 characters. Each character in the password must be
randomly selected from ASCII values ranging from 33 to 126. The function should not take
any parameters and must return the generated password. The randomly generated
password should be displayed in the main program. The main program should execute only
when the file is run directly and not when it is imported into another file.

Analysis of the Problem:


This experiment focuses on function creation, random number generation, ASCII character
handling, and the use of conditional execution in Python. The password length is
determined randomly within a specified range. ASCII values between 33 and 126 include
special characters, numbers, and letters, making the password strong and secure. The chr()
function is used to convert ASCII values into characters. The if __name__ == '__main__'
condition ensures that the main program runs only when the script is executed directly.
This experiment improves understanding of functions, randomness, and modular
programming concepts.

Algorithm:
1. Start
2. Import the random module
3. Define a function to generate a random password
4. Generate a random password length between 7 and 10
5. Initialize an empty string for the password
6. Generate random ASCII values between 33 and 126
7. Convert ASCII values to characters using chr()
8. Append each character to the password
9. Return the generated password
10. In the main program, call the function and display the password
11. Stop

Procedure:
1. Start the computer system and ensure Python is properly installed.
2. Open a Python development environment such as IDLE or Visual Studio Code.
3. Create a new Python file and name it appropriately (e.g., random_password.py).
4. Import the random module to generate random numbers.
5. Define a function that does not accept any parameters.
6. Inside the function, generate a random integer between 7 and 10 to decide the password
length.
7. Use a loop to generate random ASCII values between 33 and 126.
8. Convert each ASCII value to a character using the chr() function.
9. Append each character to form the password string.
10. Return the generated password from the function.
11. Use the if __name__ == '__main__' condition to call the function.
12. Display the randomly generated password.
13. Execute the program and verify the output.

Program:
# Experiment 3: Random Password Generator

import random

def generate_password():
# Generate random password length between 7 and 10
password_length = [Link](7, 10)

# Initialize empty password string


password = ""

# Generate random characters using ASCII values


for i in range(password_length):
ascii_value = [Link](33, 126)
password = password + chr(ascii_value)

# Return the generated password


return password

# Main program execution


if __name__ == "__main__":
random_password = generate_password()
print("Randomly Generated Password:", random_password)

Output:
---------------------------------
Randomly Generated Password: A$9kP@7!
---------------------------------

Conclusion:
Thus, the Python program was successfully executed to generate a random password of
length between 7 and 10 characters using ASCII values. The function returned the password
correctly, and the main program displayed the output only when executed directly.
Experiment 4: Reading and Analyzing Student Data from a CSV File Using Pandas

Problem Statement:
Write a Python program to read a CSV file containing student information such as name,
age, and grade using the Pandas library. The CSV file name should be provided by the user
at runtime. The program should display the first five rows of the DataFrame, calculate the
average age of the students, and filter out students whose grade is above a user-defined
threshold.

Analysis of the Problem:


In real-world applications, data files are not always fixed and may vary based on user
requirements. This program allows the user to input the CSV file name dynamically, making
the solution flexible. Pandas is used to load the CSV file into a DataFrame for efficient data
manipulation. Displaying the first five rows helps in understanding the dataset structure.
The average age is computed using aggregation functions, and conditional filtering is
applied based on a threshold entered by the user.

Algorithm:
1. Start
2. Import the Pandas library
3. Read the CSV file name from the user
4. Load the CSV file into a DataFrame
5. Display the first five rows of the DataFrame
6. Calculate the average age of the students
7. Read the grade threshold from the user
8. Filter students with grades above the threshold
9. Display the filtered student records
10. Stop

Procedure:
1. Ensure Python and the Pandas library are installed on the system.
2. Prepare a CSV file containing student details such as name, age, and grade.
3. Open a Python development environment such as IDLE or Visual Studio Code.
4. Create a new Python file and save it in the same directory as the CSV file.
5. Import the Pandas library in the Python program.
6. Prompt the user to enter the CSV file name at runtime.
7. Use the read_csv() function to load the specified CSV file into a DataFrame.
8. Display the first five rows of the DataFrame using the head() method.
9. Calculate the average age of students using the mean() function.
10. Prompt the user to enter the grade threshold value.
11. Apply conditional filtering to select students with grades above the threshold.
12. Display the filtered student details.
13. Execute the program and verify the output.

Program:
# Experiment 4: Reading CSV File using Pandas with User Input

import pandas as pd

# Reading CSV file name from user


file_name = input("Enter CSV file name: ")

# Reading the CSV file


students_df = pd.read_csv(file_name)

# Displaying the first five rows


print("\nFirst Five Rows of the DataFrame:")
print(students_df.head())

# Calculating the average age


average_age = students_df["Age"].mean()
print("\nAverage Age of Students:", average_age)

# Reading grade threshold from user


grade_threshold = int(input("\nEnter grade threshold: "))

# Filtering students based on threshold


filtered_students = students_df[students_df["Grade"] > grade_threshold]

print("\nStudents with Grade above", grade_threshold, ":")


print(filtered_students)
Output:
---------------------------------
Enter CSV file name: [Link]

First Five Rows of the DataFrame:


Name Age Grade
0 Arun 20 85
1 Bala 21 88
2 Charan 22 90
3 Divya 23 92
4 Esha 20 80

Average Age of Students: 21.2

Enter grade threshold: 85

Students with Grade above 85:


Name Age Grade
1 Bala 21 88
2 Charan 22 90
3 Divya 23 92
---------------------------------

Conclusion:
Thus, the Python program was successfully executed to read a user-specified CSV file using
Pandas. The first five rows were displayed, the average age was calculated, and students
with grades above the user-defined threshold were filtered and displayed correctly.
Experiment 5: Statistical Analysis using NumPy Array and Pandas DataFrame

Problem Statement:
Write a Python program to create a NumPy array containing random numbers based on
user-defined dimensions and convert it into a Pandas DataFrame with appropriate column
names. The program should calculate the mean, median, and standard deviation of the data
using both NumPy and Pandas functions.

Analysis of the Problem:


This experiment focuses on integrating NumPy and Pandas for numerical and statistical
analysis. The user provides the size of the dataset, which makes the program dynamic and
flexible. NumPy is used to generate random numerical data efficiently, while Pandas
provides a structured DataFrame format for better data handling and analysis. Statistical
measures such as mean, median, and standard deviation are calculated using both NumPy
and Pandas to understand how similar operations can be performed using different
libraries. This experiment helps students understand data conversion, statistical
computation, and comparison of NumPy and Pandas functionalities.

Algorithm:
1. Start
2. Import NumPy and Pandas libraries
3. Read number of rows and columns from the user
4. Generate a NumPy array with random numbers
5. Create column names for the DataFrame
6. Convert the NumPy array into a Pandas DataFrame
7. Calculate mean using NumPy
8. Calculate median using NumPy
9. Calculate standard deviation using NumPy
10. Calculate mean using Pandas
11. Calculate median using Pandas
12. Calculate standard deviation using Pandas
13. Display all results
14. Stop

Procedure:
1. Ensure that Python is installed on the system.
2. Install required libraries NumPy and Pandas if not already installed.
3. Open a Python development environment such as IDLE or Visual Studio Code.
4. Create a new Python file and name it appropriately (e.g., numpy_pandas_stats.py).
5. Import NumPy and Pandas libraries in the program.
6. Prompt the user to enter the number of rows for the NumPy array.
7. Prompt the user to enter the number of columns for the NumPy array.
8. Generate a NumPy array with random integer values.
9. Create suitable column names for the DataFrame.
10. Convert the NumPy array into a Pandas DataFrame.
11. Use NumPy functions to calculate mean, median, and standard deviation.
12. Use Pandas functions to calculate mean, median, and standard deviation.
13. Display the DataFrame and all calculated statistical values.
14. Execute the program and verify the output.

Program:
# Experiment 5: NumPy and Pandas Statistical Analysis

import numpy as np
import pandas as pd

# Reading user inputs


rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))

# Generating NumPy array with random numbers


numpy_array = [Link](10, 100, size=(rows, cols))

print("\nGenerated NumPy Array:")


print(numpy_array)

# Creating column names


column_names = []
for i in range(cols):
column_names.append("Column_" + str(i+1))

# Converting NumPy array to Pandas DataFrame


df = [Link](numpy_array, columns=column_names)

print("\nConverted Pandas DataFrame:")


print(df)

# Statistical operations using NumPy


print("\nStatistics using NumPy:")
print("Mean:", [Link](numpy_array))
print("Median:", [Link](numpy_array))
print("Standard Deviation:", [Link](numpy_array))

# Statistical operations using Pandas


print("\nStatistics using Pandas:")
print("Mean:\n", [Link]())
print("Median:\n", [Link]())
print("Standard Deviation:\n", [Link]())

Output:
---------------------------------
Enter number of rows: 3
Enter number of columns: 3

Generated NumPy Array:


[[45 67 89]
[34 56 78]
[23 65 90]]

Converted Pandas DataFrame:


Column_1 Column_2 Column_3
0 45 67 89
1 34 56 78
2 23 65 90

Statistics using NumPy:


Mean: 60.78
Median: 65.0
Standard Deviation: 22.14

Statistics using Pandas:


Mean:
Column_1 34.0
Column_2 62.7
Column_3 85.7
dtype: float64
---------------------------------

Conclusion:
Thus, the Python program was successfully executed to generate a NumPy array with
random numbers based on user input and convert it into a Pandas DataFrame. Statistical
measures such as mean, median, and standard deviation were calculated using both NumPy
and Pandas, and the results were verified.

Experiment 6: Scatter Plot with Trendline using Matplotlib and Linear Regression

Problem Statement:
Write a Python program to create a scatter plot using Matplotlib to visualize the
relationship between two variables in a dataset. The values of the variables should be
entered by the user. Add a trendline to the scatter plot using linear regression to show the
relationship between the two variables.

Analysis of the Problem:


This experiment focuses on data visualization and understanding the relationship between
two numerical variables. Scatter plots are useful for identifying patterns, trends, and
correlations between variables. Linear regression is applied to find the best-fit line that
represents the overall trend in the data. User input is used to make the program dynamic,
allowing different datasets to be analyzed. Matplotlib is used for plotting, while NumPy is
used to perform linear regression calculations. This experiment enhances understanding of
visualization and basic regression concepts.

Algorithm:
1. Start
2. Import NumPy and Matplotlib libraries
3. Read number of data points from the user
4. Read values of X and Y variables from the user
5. Store values in lists or arrays
6. Create a scatter plot using Matplotlib
7. Apply linear regression to calculate slope and intercept
8. Generate trendline values using regression equation
9. Plot the trendline on the scatter plot
10. Add labels, title, and legend
11. Display the plot
12. Stop

Procedure:
1. Ensure that Python is installed on the system.
2. Install required libraries NumPy and Matplotlib if they are not already installed.
3. Open a Python development environment such as IDLE or Visual Studio Code.
4. Create a new Python file and name it appropriately (e.g., scatter_trendline.py).
5. Import NumPy for numerical operations and Matplotlib for plotting.
6. Prompt the user to enter the number of data points.
7. Use a loop to read values for the X variable from the user.
8. Use another loop to read values for the Y variable from the user.
9. Convert the input values into NumPy arrays.
10. Create a scatter plot to visualize the data points.
11. Apply linear regression using NumPy to calculate the best-fit line.
12. Generate Y values for the trendline using the regression equation.
13. Plot the trendline along with the scatter plot.
14. Add appropriate labels, title, and legend.
15. Display the final graph and verify the output.

Program:
# Experiment 6: Scatter Plot with Trendline using Linear Regression

import numpy as np
import [Link] as plt

# Reading number of data points


n = int(input("Enter number of data points: "))

x_values = []
y_values = []

# Reading X values from user


print("Enter X values:")
for i in range(n):
x = float(input(f"X[{i+1}]: "))
x_values.append(x)

# Reading Y values from user


print("Enter Y values:")
for i in range(n):
y = float(input(f"Y[{i+1}]: "))
y_values.append(y)

# Converting lists to NumPy arrays


x_array = [Link](x_values)
y_array = [Link](y_values)

# Creating scatter plot


[Link](x_array, y_array, label='Data Points')

# Applying linear regression


slope, intercept = [Link](x_array, y_array, 1)

# Calculating trendline values


trendline = slope * x_array + intercept
# Plotting trendline
[Link](x_array, trendline, label='Trendline')

# Adding labels and title


[Link]("X Variable")
[Link]("Y Variable")
[Link]("Scatter Plot with Trendline")
[Link]()

# Displaying the plot


[Link]()

Output:
---------------------------------
Enter number of data points: 5
Enter X values:
X[1]: 1
X[2]: 2
X[3]: 3
X[4]: 4
X[5]: 5
Enter Y values:
Y[1]: 2
Y[2]: 4
Y[3]: 6
Y[4]: 8
Y[5]: 10

Scatter plot with trendline is displayed.


---------------------------------

Conclusion:
Thus, the Python program was successfully executed to visualize the relationship between
two variables using a scatter plot. A trendline was added using linear regression to
represent the overall relationship between the variables, and the output was verified.
Experiment 7: Correlation Heatmap using Seaborn
Problem Statement:
Write a Python program to create a heatmap using the Seaborn library to visualize the
correlation matrix of a dataset. The dataset values should be entered by the user. The
program should compute the correlation matrix, customize the colour palette, and add
annotations to the heatmap for better interpretation.

Analysis of the Problem:


This experiment focuses on understanding relationships between multiple numerical
variables in a dataset. Correlation matrices help identify the strength and direction of
relationships between variables. Seaborn provides advanced visualization capabilities for
statistical data. By using a heatmap with customized colour palettes and annotations,
correlations become visually interpretable. User input makes the program flexible, allowing
different datasets to be analyzed. This experiment enhances skills in data analysis,
visualization, and interpretation.

Algorithm:
1. Start
2. Import NumPy, Pandas, Matplotlib, and Seaborn libraries
3. Read number of rows and columns from the user
4. Read dataset values from the user
5. Store the values in a NumPy array
6. Convert the array into a Pandas DataFrame
7. Compute the correlation matrix
8. Create a heatmap using Seaborn
9. Customize the colour palette
10. Add annotations to the heatmap
11. Display the heatmap
12. Stop

Procedure:
1. Ensure Python is installed on the system.
2. Install required libraries such as NumPy, Pandas, Matplotlib, and Seaborn.
3. Open a Python development environment like IDLE or Visual Studio Code.
4. Create a new Python file and save it with an appropriate name.
5. Import the required libraries in the program.
6. Prompt the user to enter the number of rows in the dataset.
7. Prompt the user to enter the number of columns in the dataset.
8. Use nested loops to read dataset values from the user.
9. Convert the input values into a NumPy array.
10. Convert the NumPy array into a Pandas DataFrame with column names.
11. Calculate the correlation matrix using the corr() function.
12. Create a heatmap using Seaborn’s heatmap() function.
13. Customize the colour palette and enable annotations.
14. Add a title to the heatmap.
15. Display the heatmap and verify the output.

Program:
# Experiment 7: Correlation Heatmap using Seaborn

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

# Reading user inputs


rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))

data = []
print("Enter dataset values:")
for i in range(rows):
row = []
for j in range(cols):
value = float(input(f"Value[{i+1}][{j+1}]: "))
[Link](value)
[Link](row)

# Creating NumPy array


array = [Link](data)

# Creating column names


columns = []
for i in range(cols):
[Link]("Var_" + str(i+1))

# Converting to Pandas DataFrame


df = [Link](array, columns=columns)

# Calculating correlation matrix


correlation_matrix = [Link]()

print("\nCorrelation Matrix:")
print(correlation_matrix)

# Plotting heatmap
[Link](correlation_matrix, annot=True, cmap="coolwarm")
[Link]("Correlation Heatmap")
[Link]()

Output:
---------------------------------
Enter number of rows: 4
Enter number of columns: 3
Dataset entered successfully.

Correlation matrix displayed.


Heatmap with annotations and custom colour palette is displayed.
---------------------------------

Conclusion:
Thus, the Python program was successfully executed to visualize the correlation matrix of a
dataset using a heatmap. The colour palette was customized and annotations were added to
improve clarity and interpretation of the relationships between variables.
Experiment 8: Multiple Subplots with Line Plots using Matplotlib
Problem Statement:
Write a Python program to create a figure with multiple subplots using Matplotlib. The
program should plot multiple line plots on different subplots to visualize the trends of
different variables. The values for the variables should be provided by the user. Legends
must be added and the appearance of each subplot should be customized.

Analysis of the Problem:


This experiment focuses on visualizing multiple variables simultaneously using subplots.
Subplots allow multiple graphs to be displayed within a single figure, making it easier to
compare trends across variables. Line plots are commonly used to show trends over time or
across ordered data points. By customizing subplot appearance and adding legends, the
visualization becomes more informative and easier to interpret. User input makes the
program flexible and applicable to various datasets.

Algorithm:
1. Start
2. Import Matplotlib and NumPy libraries
3. Read number of data points from the user
4. Read values for different variables from the user
5. Create a figure with multiple subplots
6. Plot line graphs on each subplot
7. Customize line style, color, and markers
8. Add titles and axis labels to each subplot
9. Add legends to each subplot
10. Adjust layout for better appearance
11. Display the figure
12. Stop

Procedure:
1. Ensure that Python is installed on the system.
2. Install the Matplotlib and NumPy libraries if not already installed.
3. Open a Python development environment such as IDLE or Visual Studio Code.
4. Create a new Python file and save it with an appropriate name.
5. Import Matplotlib for plotting and NumPy for handling numerical data.
6. Prompt the user to enter the number of data points.
7. Use loops to read values for multiple variables from the user.
8. Create a Matplotlib figure with multiple subplots.
9. Plot each variable on a separate subplot using line plots.
10. Customize line colors, markers, and line styles for clarity.
11. Add titles, axis labels, and legends to each subplot.
12. Adjust spacing between subplots using layout functions.
13. Display the final figure.
14. Verify the plotted trends.
15. Record the observations.

Program:
# Experiment 8: Multiple Subplots with Line Plots

import [Link] as plt


import numpy as np

# Reading number of data points


n = int(input("Enter number of data points: "))

x_values = []
y1_values = []
y2_values = []

# Reading X values
print("Enter X values:")
for i in range(n):
x = float(input(f"X[{i+1}]: "))
x_values.append(x)

# Reading first Y variable values


print("Enter Y1 values:")
for i in range(n):
y1 = float(input(f"Y1[{i+1}]: "))
y1_values.append(y1)

# Reading second Y variable values


print("Enter Y2 values:")
for i in range(n):
y2 = float(input(f"Y2[{i+1}]: "))
y2_values.append(y2)

# Converting lists to NumPy arrays


x = [Link](x_values)
y1 = [Link](y1_values)
y2 = [Link](y2_values)

# Creating subplots
fig, axes = [Link](2, 1)

# First subplot
axes[0].plot(x, y1, color='blue', marker='o', label='Variable Y1')
axes[0].set_title("Trend of Variable Y1")
axes[0].set_xlabel("X Values")
axes[0].set_ylabel("Y1 Values")
axes[0].legend()

# Second subplot
axes[1].plot(x, y2, color='green', marker='s', label='Variable Y2')
axes[1].set_title("Trend of Variable Y2")
axes[1].set_xlabel("X Values")
axes[1].set_ylabel("Y2 Values")
axes[1].legend()

# Adjust layout
plt.tight_layout()

# Display the figure


[Link]()

Output:
---------------------------------
Enter number of data points: 5
Enter X values and Y values.

Multiple subplots with line plots are displayed.


---------------------------------

Conclusion:
Thus, the Python program was successfully executed to create a figure with multiple
subplots using Matplotlib. Line plots were drawn on different subplots to visualize trends of
different variables, and legends along with customized appearance improved the clarity of
the visualization.

Experiment 9: Handling Missing Data using Pandas


Problem Statement:
Write a Python program to handle missing data in a dataset using the Pandas library. The
program should read a dataset provided by the user and implement various techniques
such as dropping missing values, filling missing values with mean or median, and forward
filling and backward filling methods.

Analysis of the Problem:


In real-world datasets, missing values are very common due to data collection errors,
incomplete records, or system failures. Handling missing data is a crucial step in data
preprocessing. Pandas provides several built-in functions to detect and handle missing
values efficiently. Dropping missing values may reduce dataset size, while filling missing
values using statistical measures like mean or median helps retain data. Forward and
backward filling techniques are useful when data has a sequential order. This experiment
helps in understanding practical data cleaning techniques.

Algorithm:
1. Start
2. Import the Pandas and NumPy libraries
3. Read the dataset file name from the user
4. Load the dataset into a DataFrame
5. Display the original dataset
6. Drop rows with missing values
7. Fill missing values with mean
8. Fill missing values with median
9. Apply forward fill method
10. Apply backward fill method
11. Display the processed datasets
12. Stop

Procedure:
1. Ensure Python and required libraries Pandas and NumPy are installed.
2. Prepare a dataset file (CSV) containing missing values.
3. Open a Python development environment such as IDLE or Visual Studio Code.
4. Create a new Python file and save it in the same directory as the dataset file.
5. Import Pandas and NumPy libraries in the program.
6. Prompt the user to enter the dataset file name.
7. Read the dataset into a Pandas DataFrame.
8. Display the original dataset with missing values.
9. Apply dropna() to remove rows with missing values.
10. Apply fillna() using mean values.
11. Apply fillna() using median values.
12. Apply forward fill (ffill) method.
13. Apply backward fill (bfill) method.
14. Display the results of each operation.
15. Verify the output.

Program:
# Experiment 9: Handling Missing Data using Pandas

import pandas as pd
import numpy as np

# Reading dataset file name from user


file_name = input("Enter dataset CSV file name: ")

# Loading dataset
df = pd.read_csv(file_name)

print("\nOriginal Dataset:")
print(df)

# Dropping rows with missing values


drop_df = [Link]()
print("\nDataset after dropping missing values:")
print(drop_df)

# Filling missing values with mean


mean_fill_df = [Link]([Link](numeric_only=True))
print("\nDataset after filling missing values with mean:")
print(mean_fill_df)
# Filling missing values with median
median_fill_df = [Link]([Link](numeric_only=True))
print("\nDataset after filling missing values with median:")
print(median_fill_df)

# Forward fill
ffill_df = [Link](method='ffill')
print("\nDataset after forward fill:")
print(ffill_df)

# Backward fill
bfill_df = [Link](method='bfill')
print("\nDataset after backward fill:")
print(bfill_df)

Output:
---------------------------------
Enter dataset CSV file name: [Link]

Original Dataset:
A B C
0 10 20.0 NaN
1 NaN 30.0 40
2 50 NaN 60

Dataset after dropping missing values:


A B C
(no missing rows)

Dataset after filling missing values with mean:


Values filled successfully

Dataset after forward fill:


Values filled successfully

Dataset after backward fill:


Values filled successfully
---------------------------------
Conclusion:
Thus, the Python program was successfully executed to handle missing data using Pandas.
Different techniques such as dropping missing values, filling with mean and median, and
forward and backward filling methods were implemented and verified.

Experiment 10: Feature Hashing of Categorical Data using Scikit-learn


Problem Statement:
Write a Python program to perform feature hashing on a categorical variable using Pandas
or Scikit-learn. The program should read categorical values from the user and convert them
into a numerical format by applying a hash function. Feature hashing should be used to
transform categorical data into a fixed-length numerical feature vector.

Analysis of the Problem:


Machine learning algorithms require numerical input data, but real-world datasets often
contain categorical variables such as names, locations, or product categories. Feature
hashing is an efficient technique used to convert categorical variables into numerical form
without creating large dictionaries. Scikit-learn provides the FeatureHasher class, which
applies a hash function to categorical values and maps them into a fixed-size numerical
vector. This method is memory efficient and suitable for large datasets. User input is used to
make the program dynamic.

Algorithm:
1. Start
2. Import required libraries from Scikit-learn and Pandas
3. Read number of categorical values from the user
4. Read categorical values from the user
5. Store the values in a list
6. Initialize the FeatureHasher with a fixed number of features
7. Apply feature hashing on the categorical values
8. Convert the hashed output into a readable format
9. Display the hashed numerical features
10. Stop

Procedure:
1. Ensure Python is installed on the system.
2. Install required libraries such as Pandas and Scikit-learn.
3. Open a Python development environment like IDLE or Visual Studio Code.
4. Create a new Python file and save it with an appropriate name.
5. Import the FeatureHasher class from Scikit-learn.
6. Prompt the user to enter the number of categorical values.
7. Use a loop to read categorical values from the user.
8. Store the categorical values in a list.
9. Initialize the FeatureHasher with a chosen number of features.
10. Apply the hashing transformation to the categorical data.
11. Convert the hashed output to an array format.
12. Display the hashed numerical representation.
13. Execute the program and verify the output.

Program:
# Experiment 10: Feature Hashing using Scikit-learn

from sklearn.feature_extraction import FeatureHasher


import pandas as pd

# Reading number of categorical values from user


n = int(input("Enter number of categorical values: "))

categories = []

# Reading categorical values


for i in range(n):
value = input(f"Enter category {i+1}: ")
[Link](value)

# Initializing FeatureHasher
hasher = FeatureHasher(n_features=8, input_type='string')

# Applying feature hashing


hashed_features = [Link](categories)

# Converting hashed features to array


hashed_array = hashed_features.toarray()

# Displaying the result


print("\nCategorical Values:")
print(categories)

print("\nHashed Feature Representation:")


print(hashed_array)

Output:
---------------------------------
Enter number of categorical values: 3
Enter category 1: Apple
Enter category 2: Banana
Enter category 3: Orange

Categorical Values:
['Apple', 'Banana', 'Orange']

Hashed Feature Representation:


[[ 0. 1. 0. -1. 0. 0. 0. 0.]
[ 1. 0. 0. 0. 0. -1. 0. 0.]
[ 0. 0. 1. 0. 0. 0. -1. 0.]]
---------------------------------
\

Conclusion:
Thus, the Python program was successfully executed to convert categorical variables into
numerical format using feature hashing. The Scikit-learn FeatureHasher efficiently
transformed the categorical data into fixed-length numerical feature vectors suitable for
machine learning models.

Experiment 11: Merging Datasets using Pandas (Inner, Left, and Right Join)
Problem Statement:
Write a Python program to merge two datasets based on a common column using the
Pandas library. The program should read two dataset file names from the user and perform
inner join, left join, and right join operations between the datasets. The merged results of
each join operation should be displayed.

Analysis of the Problem:


In real-world data analysis, information is often stored across multiple datasets. To analyze
such data effectively, it is necessary to combine datasets based on a common key or column.
Pandas provides powerful merge functions that allow different types of joins such as inner,
left, and right joins. An inner join returns only matching records from both datasets, a left
join returns all records from the first dataset and matching records from the second, while a
right join returns all records from the second dataset and matching records from the first.
User input makes the program flexible and suitable for different datasets.

Algorithm:
1. Start
2. Import the Pandas library
3. Read first dataset file name from the user
4. Read second dataset file name from the user
5. Read the common column name from the user
6. Load both datasets into DataFrames
7. Perform inner join using the common column
8. Perform left join using the common column
9. Perform right join using the common column
10. Display the merged results
11. Stop

Procedure:
1. Ensure Python and the Pandas library are installed on the system.
2. Prepare two CSV files containing related data with at least one common column.
3. Open a Python development environment such as IDLE or Visual Studio Code.
4. Create a new Python file and save it in the same directory as the CSV files.
5. Import the Pandas library in the Python program.
6. Prompt the user to enter the first dataset file name.
7. Prompt the user to enter the second dataset file name.
8. Prompt the user to enter the common column name used for merging.
9. Load both datasets into Pandas DataFrames.
10. Apply inner join using the merge() function.
11. Apply left join using the merge() function.
12. Apply right join using the merge() function.
13. Display the output of each join operation.
14. Execute the program and verify the results.
15. Record the observations.

Program:
# Experiment 11: Merging Datasets using Pandas

import pandas as pd

# Reading dataset file names from user


file1 = input("Enter first CSV file name: ")
file2 = input("Enter second CSV file name: ")

# Reading common column name


common_column = input("Enter common column name for merge: ")

# Loading datasets
df1 = pd.read_csv(file1)
df2 = pd.read_csv(file2)

print("\nFirst Dataset:")
print(df1)

print("\nSecond Dataset:")
print(df2)

# Inner join
inner_join = [Link](df1, df2, on=common_column, how='inner')
print("\nInner Join Result:")
print(inner_join)

# Left join
left_join = [Link](df1, df2, on=common_column, how='left')
print("\nLeft Join Result:")
print(left_join)

# Right join
right_join = [Link](df1, df2, on=common_column, how='right')
print("\nRight Join Result:")
print(right_join)

Output:
---------------------------------
Enter first CSV file name: [Link]
Enter second CSV file name: [Link]
Enter common column name for merge: id
Inner Join Result:
(Matching records displayed)

Left Join Result:


(All records from first dataset displayed)

Right Join Result:


(All records from second dataset displayed)
---------------------------------

Conclusion:
Thus, the Python program was successfully executed to merge two datasets using Pandas.
Inner join, left join, and right join operations were performed based on a common column,
and the merged results were displayed and verified.
Experiment 12: Box Plot Visualization using Matplotlib / Seaborn
Problem Statement:
Write a Python program to create a box plot using Matplotlib or Seaborn to visualize the
distribution of a numerical variable across different categories. The dataset should be
provided by the user. Appropriate labels and titles must be added to the box plot for clear
interpretation.

Analysis of the Problem:


Box plots are a statistical visualization technique used to display the distribution of
numerical data across different categories. They provide information about the median,
quartiles, range, and presence of outliers in the data. By grouping numerical values under
categories, box plots allow easy comparison between distributions. Matplotlib and Seaborn
offer built-in functions to generate box plots efficiently. User input makes the program
flexible and applicable to various datasets. This experiment helps in understanding data
distribution and comparative analysis.

Algorithm:
1. Start
2. Import required libraries (Pandas, Matplotlib, Seaborn)
3. Read dataset file name from the user
4. Read categorical column name from the user
5. Read numerical column name from the user
6. Load the dataset into a DataFrame
7. Create a box plot grouped by category
8. Add title and axis labels
9. Customize appearance of the plot
10. Display the box plot
11. Stop

Procedure:
1. Ensure Python and required libraries Pandas, Matplotlib, and Seaborn are installed.
2. Prepare a CSV dataset containing at least one categorical column and one numerical
column.
3. Open a Python development environment such as IDLE or Visual Studio Code.
4. Create a new Python file and save it in the same directory as the dataset file.
5. Import Pandas for data handling and Matplotlib/Seaborn for visualization.
6. Prompt the user to enter the dataset file name.
7. Prompt the user to enter the categorical column name.
8. Prompt the user to enter the numerical column name.
9. Load the dataset into a Pandas DataFrame.
10. Use Seaborn or Matplotlib to create a box plot grouped by category.
11. Add appropriate title and axis labels.
12. Customize the plot appearance such as colors and grid.
13. Display the box plot.
14. Verify the output visually.
15. Record the observations.

Program:
# Experiment 12: Box Plot Visualization

import pandas as pd
import seaborn as sns
import [Link] as plt

# Reading dataset file name from user


file_name = input("Enter CSV file name: ")

# Reading column names from user


category_column = input("Enter categorical column name: ")
numeric_column = input("Enter numerical column name: ")

# Loading dataset
df = pd.read_csv(file_name)

print("\nDataset Preview:")
print([Link]())

# Creating box plot


[Link](figsize=(8, 6))
[Link](x=category_column, y=numeric_column, data=df)

# Adding labels and title


[Link](category_column)
[Link](numeric_column)
[Link]("Box Plot of " + numeric_column + " across " + category_column)

# Display plot
[Link]()
Output:
---------------------------------
Enter CSV file name: [Link]
Enter categorical column name: Department
Enter numerical column name: Salary

Box plot showing distribution of Salary across Department is displayed.


---------------------------------
Conclusion:
Thus, the Python program was successfully executed to visualize the distribution of a
numerical variable across different categories using a box plot. Appropriate labels and titles
were added, and the visualization helped in comparing data distributions effectively.
Experiment 13: Bar Chart and Stacked Bar Chart using Matplotlib / Seaborn

Problem Statement:
Write a Python program to create a bar chart or stacked bar chart using Matplotlib or
Seaborn to compare the frequency distribution of a categorical variable across different
groups or categories in a dataset. The dataset and column names should be provided by the
user. Appropriate labels, legends, and titles must be added to the chart.

Analysis of the Problem:


Bar charts are widely used to compare categorical data across different groups. A simple bar
chart shows the frequency or count of categories, while a stacked bar chart allows
comparison of sub-categories within each category. This experiment helps in understanding
group-wise comparison, frequency distribution, and categorical data visualization. Using
Matplotlib or Seaborn, these visualizations can be customized for clarity and better
interpretation. User input makes the program flexible for different datasets.

Algorithm:
1. Start
2. Import Pandas, Matplotlib, and Seaborn libraries
3. Read dataset file name from the user
4. Read main categorical column name from the user
5. Read group/category column name from the user
6. Load the dataset into a DataFrame
7. Compute frequency counts using groupby
8. Create a bar chart or stacked bar chart
9. Add labels, title, and legend
10. Display the chart
11. Stop

Procedure:
1. Ensure Python and required libraries Pandas, Matplotlib, and Seaborn are installed.
2. Prepare a CSV dataset containing categorical variables.
3. Open a Python development environment such as IDLE or Visual Studio Code.
4. Create a new Python file and save it in the same directory as the dataset file.
5. Import Pandas for data handling and Matplotlib/Seaborn for visualization.
6. Prompt the user to enter the dataset file name.
7. Prompt the user to enter the categorical column for comparison.
8. Prompt the user to enter the grouping column.
9. Load the dataset into a Pandas DataFrame.
10. Group the data and calculate frequency counts.
11. Create a bar chart or stacked bar chart.
12. Add axis labels, legend, and title.
13. Customize colors and appearance.
14. Display the chart.
15. Verify the output.

Program:
# Experiment 13: Bar Chart and Stacked Bar Chart

import pandas as pd
import [Link] as plt

# Reading dataset file name from user


file_name = input("Enter CSV file name: ")

# Reading column names


category_column = input("Enter categorical column name: ")
group_column = input("Enter grouping column name: ")

# Loading dataset
df = pd.read_csv(file_name)

print("\nDataset Preview:")
print([Link]())

# Creating frequency table


frequency_table = [Link](df[group_column], df[category_column])

print("\nFrequency Table:")
print(frequency_table)

# Plotting stacked bar chart


frequency_table.plot(kind='bar', stacked=True)

# Adding labels and title


[Link](group_column)
[Link]("Frequency")
[Link]("Stacked Bar Chart of " + category_column + " across " + group_column)
[Link](title=category_column)

# Display plot
[Link]()
Output:
---------------------------------
Enter CSV file name: [Link]
Enter categorical column name: Product
Enter grouping column name: Region

Bar chart / stacked bar chart comparing frequency distribution is displayed.


---------------------------------
Conclusion:
Thus, the Python program was successfully executed to compare frequency distributions of
categorical variables using bar and stacked bar charts. The visualization clearly showed
group-wise differences and helped in effective comparison of categorical data.
Experiment 14: Correlation Analysis using NumPy / Pandas

Problem Statement:
Write a Python program to perform correlation analysis between two numerical variables
in a dataset using NumPy or Pandas. The program should calculate the correlation
coefficient and visualize the correlation using a scatter plot. The dataset and column names
should be provided by the user.

Analysis of the Problem:


Correlation analysis is used to measure the strength and direction of the relationship
between two numerical variables. The correlation coefficient ranges between -1 and +1,
where values close to +1 indicate strong positive correlation, values close to -1 indicate
strong negative correlation, and values near 0 indicate weak or no correlation. NumPy and
Pandas provide built-in functions to compute correlation efficiently. Scatter plots are used
to visually represent the relationship between variables. This experiment helps in
understanding statistical relationships and data interpretation.

Algorithm:
1. Start
2. Import Pandas, NumPy, and Matplotlib libraries
3. Read dataset file name from the user
4. Read first numerical column name from the user
5. Read second numerical column name from the user
6. Load the dataset into a DataFrame
7. Extract the two numerical columns
8. Calculate correlation coefficient using NumPy or Pandas
9. Create a scatter plot to visualize correlation
10. Add labels and title
11. Display correlation value and plot
12. Stop

Procedure:
1. Ensure Python and required libraries Pandas, NumPy, and Matplotlib are installed.
2. Prepare a CSV dataset containing numerical variables.
3. Open a Python development environment such as IDLE or Visual Studio Code.
4. Create a new Python file and save it in the same directory as the dataset file.
5. Import Pandas, NumPy, and Matplotlib libraries.
6. Prompt the user to enter the dataset file name.
7. Prompt the user to enter the first numerical column name.
8. Prompt the user to enter the second numerical column name.
9. Load the dataset into a Pandas DataFrame.
10. Extract the selected numerical columns.
11. Calculate the correlation coefficient.
12. Create a scatter plot to visualize the relationship.
13. Add axis labels, title, and grid to the plot.
14. Display the correlation value and scatter plot.
15. Verify the output.

Program:
# Experiment 14: Correlation Analysis using NumPy and Pandas

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

# Reading dataset file name


file_name = input("Enter CSV file name: ")

# Reading column names


col1 = input("Enter first numerical column name: ")
col2 = input("Enter second numerical column name: ")

# Loading dataset
df = pd.read_csv(file_name)

# Extracting columns
x = df[col1]
y = df[col2]

# Calculating correlation coefficient


correlation = [Link](x, y)[0, 1]

print("\nCorrelation Coefficient:", correlation)

# Creating scatter plot


[Link](x, y)
[Link](col1)
[Link](col2)
[Link]("Scatter Plot showing Correlation between Variables")
[Link](True)

# Display plot
[Link]()

Output:
---------------------------------
Enter CSV file name: [Link]
Enter first numerical column name: Height
Enter second numerical column name: Weight

Correlation Coefficient: 0.92

Scatter plot showing correlation is displayed.


---------------------------------

Conclusion:
Thus, the Python program was successfully executed to perform correlation analysis
between two numerical variables. The correlation coefficient was calculated and the
relationship between variables was visually represented using a scatter plot.

You might also like