Python Lab Manual
Python Lab Manual
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.
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)
Output:
---------------------------------
Enter first number: 8
Enter second number: 3
Enter third number: 5
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.
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
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.
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)
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.
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
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.
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
Output:
---------------------------------
Enter number of rows: 3
Enter number of columns: 3
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.
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
x_values = []
y_values = []
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
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.
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
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)
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.
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.
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
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)
# 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()
Output:
---------------------------------
Enter number of data points: 5
Enter X values and Y values.
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.
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
# Loading dataset
df = pd.read_csv(file_name)
print("\nOriginal Dataset:")
print(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
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
categories = []
# Initializing FeatureHasher
hasher = FeatureHasher(n_features=8, input_type='string')
Output:
---------------------------------
Enter number of categorical values: 3
Enter category 1: Apple
Enter category 2: Banana
Enter category 3: Orange
Categorical Values:
['Apple', 'Banana', 'Orange']
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.
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
# 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)
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.
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
# Loading dataset
df = pd.read_csv(file_name)
print("\nDataset Preview:")
print([Link]())
# Display plot
[Link]()
Output:
---------------------------------
Enter CSV file name: [Link]
Enter categorical column name: Department
Enter numerical column name: Salary
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.
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
# Loading dataset
df = pd.read_csv(file_name)
print("\nDataset Preview:")
print([Link]())
print("\nFrequency Table:")
print(frequency_table)
# Display plot
[Link]()
Output:
---------------------------------
Enter CSV file name: [Link]
Enter categorical column name: Product
Enter grouping column name: Region
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.
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
# Loading dataset
df = pd.read_csv(file_name)
# Extracting columns
x = df[col1]
y = df[col2]
# Display plot
[Link]()
Output:
---------------------------------
Enter CSV file name: [Link]
Enter first numerical column name: Height
Enter second numerical column name: Weight
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.