Python Lab - Record (Exp 1 - 7)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Department of Artificial Intelligence and Data Science

PYTHON PROGRAMMING
FOR DATA SCIENCE
2023 -2024

STUDENT NAME ARUNAGIRINATHAN.K


SUBJECT NAME/CODE Phython Programming for Data science/ADB1121
SEMESTER/YEAR IInd/Ist

PYTHON LAB 1
EXP DATE
NO Sort the given three integers in the ascending
1 order.

AIM :
To create a Python program that reads three integers from the user and displays
them in sorted order.

ALGORITHM :
STEP:1 Read three integers from the user.

STEP:2 Use the min and max functions to find the smallest and largest values.

STEP:3 Compute the sum of all three values.

STEP:4 Calculate the middle value by subtracting the minimum and maximum
values from the sum.

STEP:5 Display the three integers in sorted order.

PROGRAM :

num1 = int(input("Enter the first integer: "))


num2 = int(input("Enter the second integer: "))
num3 = int(input("Enter the third integer: "))

smallest = min(num1, num2, num3)


largest = max(num1, num2, num3)

PYTHON LAB 2
total_sum = num1 + num2 + num3

middle = total_sum - smallest - largest

print("Integers in Sorted order: ", smallest, middle, largest )

OUTPUT:

Enter the first integer:


Enter the second integer:
Enter the third integer:
Integers in sorted order:

RESULT :

The program displays the integers in sorted order.

PYTHON LAB 3
EXP NO Finding whether a given letter is a vowel or a DATE
2 consonant

AIM:
Create a program that determines whether a given letter of the alphabet is a vowel
or a consonant.

ALGORITHM :
STEP:1 Check if the entered character is alphabetical using the isalpha()
method.

STEP:2 Read a character of the alphabet from the user.

STEP:3 Read the input character and convert it to lowercase.

STEP:4 Check if the entered character is 'a', 'e', 'i', 'o', or 'u'. If yes, display a
message indicating it's a vowel.

STEP:5 Check if the entered character is 'y'. If yes, display a message


indicating it's sometimes a vowel and sometimes a consonant.

STEP:6 If the entered character is not a vowel or 'y', display a message


indicating it's a consonant.

PROGRAM :

character = input("Enter a letter of the alphabet or a number: ").lower()


if character.isalpha():
if character in ['a', 'e', 'i', 'o', 'u']:
print("The entered character is a vowel.")
elif character == 'y':

PYTHON LAB 4
print("Sometimes y is a vowel, and sometimes y is a consonant.")
else:
print("The entered character is a consonant.")
elif character.isdigit():
print("The entered character is a number.")
else:
print("The entered character is not a letter or a number.")

OUTPUT:

Enter a letter of the alphabet or a number: a


The entered character is a vowel.

Enter a letter of the alphabet or a number: s


The entered character is a consonant.

Enter a letter of the alphabet or a number: y


Sometimes y is a vowel, and sometimes y is a consonant.

RESULT :
The program correctly identifies whether the entered letter is a vowel, consonant or
‘y’ based on the given conditions.

PYTHON LAB 5
EXP NO DATE
3 Generate a Random Password Using Function

AIM :
To create a Python function that generates a random password within the specified
criteria and display the generated password in the main program.

ALGORITHM :

STEP:1 Define a function generate_password() that takes no parameters.

STEP:2 Generate a random length for the password between 7 and 10


characters.

STEP:3 Use a loop to generate random characters for the password based on
the random length.

STEP:4 Each character should be randomly selected from positions 33 to 126


in the ASCII table.

STEP:5 Concatenate the random characters to form the password.

STEP:6 Return the generated password from the function.

STEP:7 In the main program, call the generate_password() function and


display the generated password.

PYTHON LAB 6
PROGRAM :

import random
def generate_password():
password_length = random.randint(7, 10)
password = ''
for x in range(password_length):
password += chr(random.randint(33, 126))
return password

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

OUTPUT:
Generated Password: 7WWIeK\3U\

RESULT :

The program successfully generates a random password with a length between 7


and 10 characters, with each character randomly selected from positions 33 to 126
in the ASCII table.

PYTHON LAB 7
EXP NO DATE
4 File handling using Pandas Dataframe

AIM :
The aim is to read student information from a CSV file, display the first five rows
of the data frame, calculate the average age of the students, and filter out students
with grades above a certain threshold.

ALGORITHM :
STEP:1 Import the necessary libraries, including Pandas.

STEP:2 Read the CSV file containing student information into a Pandas
DataFrame.

STEP:3 Display the first five rows of the DataFrame using the head() method.

STEP:4 Calculate the average age of the students by computing the mean of the
'age' column.

STEP:5 Prompt the user to enter a grade threshold.

STEP:6 Filter out the students with grades above the threshold using boolean
indexing.

STEP:7Display the filtered DataFrame.

PYTHON LAB 8
PROGRAM :

import pandas as pd

df = pd.read_csv(‘lab-4.csv’)

print ("First five rows of the DataFrame:")


print (df.head())

average_age = df['Age'].mean()
print ("\nAverage age of the students:", average_age)

threshold = float(input("\nEnter the grade threshold: "))

filtered_df = df[df['Grade'] <= threshold]

print ("\nStudents with grades less than or equal to the threshold:")


print (filtered_df)

PYTHON LAB 9
OUTPUT:

First five rows of the DataFrame:

ID Name Age Grade


0 NaN NaN NaN NaN
1 111111.0 John Doe 23.0 90.0
2 111112.0 Jane Smith 12.0 70.0
3 111113.0 Sarah Thomas 23.0 45.0
4 111114.0 Frank Brown 18.0 80.0

Average age of the students: 21.285714285714285

Enter the grade threshold: 30

Students with grades less than or equal to the threshold:

ID Name Age Grade


5 111115.0 Mike Davis 19.0 20.0
8 111118.0 Fred Clark 26.0 23.0
9 111119.0 Bob Lopez 20.0 12.0
11 111121.0 Ferik Anderson 24.0 23.0
13 111123.0 Feliz antony 21.0 25.0

RESULT :
Thus the program for file handling using pandas dataframe has been successfully
executed.

PYTHON LAB 10
EXP NO DATE
5 Comparing Statistical Measures: NumPy vs
Pandas

AIM :
The aim of this program is to demonstrate how to Generate a NumPy array with
random numbers, convert the same array into a Pandas DataFrame with
appropriate column names and then calculate the mean, median, and standard
deviation of the data using both NumPy and Pandas functions.

ALGORITHM :
1. Import the necessary libraries: NumPy and Pandas.

2. Generate a NumPy array with random numbers using numpy.random.rand()


function.

3. Convert the NumPy array into a Pandas DataFrame with appropriate column
names.

4. Use NumPy and Pandas functions to calculate the mean, median, and
standard deviation of the data.

5. Print the results.

PROGRAM :

import numpy as np
import pandas as pd

np_array = np.random.rand(5, 3)

PYTHON LAB 11
column_names = ['Column_1', 'Column_2', 'Column_3']
df = pd.DataFrame(np_array, columns=column_names)

mean_np = np.mean(np_array)

median_np = np.median(np_array)

std_np = np.std(np_array)

mean_pd = df.mean()
median_pd = df.median()
std_pd = df.std()

print("NumPy Mean:")
print(mean_np)
print("\nPandas Mean:")
print(mean_pd)
print("\nNumPy Median:")
print(median_np)
print("\nPandas Median:")
print(median_pd)
print("\nNumPy Standard Deviation:")

PYTHON LAB 12
print(std_np)
print("\nPandas Standard Deviation:")
print(std_pd)

OUTPUT:
NumPy Mean:
0.5107690724628491

Pandas Mean:
Column_1 0.630971
Column_2 0.559101
Column_3 0.518407
dtype: float64

NumPy Median:
0.5644428322384722

Pandas Median:
Column_1 0.676098
Column_2 0.595252
Column_3 0.481189
dtype: float64

NumPy Standard Deviation:


0.21253242293540204

PYTHON LAB 13
Pandas Standard Deviation:
Column_1 0.147784
Column_2 0.085243
Column_3 0.276785
dtype: float64

RESULT :

The program successfully demonstrates the statistical comparison of Numpy vs


Pandas

PYTHON LAB 14
EXP NO DATE
6 Comparing Statistical Measures: NumPy vs
Pandas using dataset

AIM :
The aim of this program is to demonstrate how to Generate a NumPy array with
random numbers from the dataset, convert the same array into a Pandas DataFrame
with appropriate column names and then calculate the mean, median, and standard
deviation of the data using both NumPy and Pandas functions.

ALGORITHM :
1. Import the necessary libraries: NumPy and Pandas.

2. Generate a NumPy array with dataset using dataframe creation.

3. Convert the NumPy array into a Pandas DataFrame with appropriate column
names.

4. Use NumPy and Pandas functions to calculate the mean, median, and
standard deviation of the data.

5. Print the results.

PROGRAM :
import numpy as np
import pandas as pd
np_array=np.random.rand(3,5)
df = pd.read_csv('lab-ex-6.csv')

PYTHON LAB 15
column_names = ['Tamil','English','Maths','Science','Social']
df = pd.DataFrame(np_array, columns=column_names)

mean_np = np.mean(np_array)
median_np = np.median(np_array)
std_np = np.std(np_array)

mean_pd = df.mean()
median_pd = df.median()
std_pd = df.std()

print("NumPy Mean:")
print(mean_np)
print("\nPandas Mean:")
print(mean_pd)
print("\nNumPy Median:")
print(median_np)
print("\nPandas Median:")
print(median_pd)
print("\nNumPy Standard Deviation:")
print(std_np)
print("\nPandas Standard Deviation:")
print(std_pd)

OUTPUT:
NumPy Mean:

0.5937982966893395

PYTHON LAB 16
Pandas Mean:

Tamil 0.217006

English 0.678402

Maths 0.585628

Science 0.613438

Social 0.874517

dtype: float64

NumPy Median:

0.6476541923679712

Pandas Median:

Tamil 0.266269

English 0.847279

Maths 0.518450

Science 0.647654

Social 0.900979

dtype: float64

PYTHON LAB 17
NumPy Standard Deviation:

0.2741247946668009

Pandas Standard Deviation:

Tamil 0.105272

English 0.312321

Maths 0.199324

Science 0.256798

Social 0.081868

dtype: float64

RESULT :

The program successfully demonstrates the statistical comparison of Numpy vs


Pandas

PYTHON LAB 18
EXP NO DATE
7 Linear Regression Trendline Plotter Using
Matplotlib

AIM :
The aim of this program is to visually represent the relationship between two
variables in a dataset using a scatter plot. Additionally, the program will utilize
linear regression to add a trendline to the scatter plot, aiding in understanding the
underlying relationship between the variables.

ALGORITHM :
 Import the necessary libraries: Matplotlib for plotting and linear regression,
and NumPy for numerical operations.

 Load or generate the dataset containing two variables.

 Create a scatter plot using Matplotlib, with one variable on the x-axis and
the other variable on the y-axis.

 Use linear regression to fit a trendline to the scatter plot data.

 Plot the trendline on the scatter plot.

 Display the scatter plot with the trendline.

PROGRAM :
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression

PYTHON LAB 19
# Generate sample data (replace this with your dataset)
df = pd.read_csv('lab-7.csv')
x = df['User ID'].values.reshape(-1, 1)
y = df['Post ID']

# Create scatter plot


plt.scatter(x, y, color='blue', label='Data Points')

# Fit linear regression model


model = LinearRegression()
model.fit(x, y)

# Get slope and intercept of the fitted line


slope = model.coef_[0]
intercept = model.intercept_

# Create trendline
trendline = slope * x + intercept
plt.plot(x, trendline, color='red', label='Trendline')

# Add labels and legend


plt.xlabel('X')
plt.ylabel('Y')
plt.title('Scatter Plot with Trendline')
plt.legend()

PYTHON LAB 20
# Show plot
plt.grid(True)
plt.show()

OUTPUT:

RESULT :
The scatter plot with the trendline provides a visual representation of the
relationship between the two variables in the dataset.

PYTHON LAB 21

You might also like