Updated Python With Data Science Lab Manual
Updated Python With Data Science Lab Manual
Date:
Program
Output:
Enter a number: 30
Enter another number: 12
d1= 12 d2= 6
The GCD of given numbers is: 6
Ex. No. 2 MAXIMUM AND MINIMUM OF A LIST OF NUMBERS
Date:
Algorithm
Step 1: Get a list of elements
Step 2: Initialize min and max variable
Step 3: Run a loop in the iteration of (i) between 0 and length of the list
a) compare ith element with max value find max value
b) compare list of element with min value find min value
Step 4 : print the result
Program:
# find min and max value from list
a = [3, 5, 7, 2, 8, 1]
# Initializing variables for max and min
mxv = a[0]
mnv = a[0]
mxp = 0
mnp = 0
Date :
Aim:
To Write a Python program to perform the following operations on the given string
Algorithm:
Step 2: Separate the string into words using “split” function- A list is generated
Step 4: Traverse the string character by character and check for vowels. Increment
Step 6: For every element in the list generated, use title() function to capitalize the
first word
Program:
s=input(“Enter a string:”)
l=[Link]()
COUNT=0
for i in s:
if (i in “aeiouAEIOU”):
COUNT=COUNT+1
for i in l:
print([Link](),end=” “)
Output:
Number of words = 3
Number of Vowels = 4
I Love Python
Ex. No. 4 DICTIONARY MANIPULATION
Date :
Aim:
To write a python program using dictionary to store student marks and find
highest mark
Algorithm:
Program :
student_marks = {
"Alice": 85,
"Bob": 92,
"Charlie": 78,
"David": 88,
"Eve": 91
}
# Find the student with the highest mark
for student, marks in student_marks.items():
if marks > highest_mark:
highest_mark = marks
highest_student = student
Output:
Aim:
To implement a program to find the most frequent words in a text read from a file.
Algorithm:
1. Variable maxCount will store the count of most repeated word.
2. Open a file in read mode using file pointer.
3. Read a line from file. Convert each line into lowercase and remove the
punctuation marks.
4. Split the line into words and store it in an array.
5. Use two loops to iterate through the array. Outer loop will select a word which
needs to be count. Inner loop will match the selected word with rest of the
array. If match found, increment count by 1.
6. If count is greater than maxCount then, store value of count in maxCount and
corresponding word in variable word.
7. At the end, maxCount will hold the maximum count and variable word will
hold most repeated word.
Program:
count = 0
word = ""
maxCount = 0
file = open("[Link]", "r")
s=[Link]()
words = [Link]()
for i in range(0,len(words)):
count = 1
for j in range(i+1,len(words)):
if(words[i] == words[j]):
count = count + 1
if(count >maxCount):
maxCount = count
word = words[i]
print("Most repeated word: " + word , maxcount , “ times” )
[Link]()
Output:
Most Repeated Word: Computer 4 times
Ex. No. 6 EXCEPTION HANDLING
Date :
Aim:
Algorithm:
Program:
print("License Process")
name = input("Name : ")
bloodgroup = input("Blood Group : ")
address = input("Address : ").strip()
while(True):
try:
age = int(input("Age: "))
break
except:
print("Enter only numbers")
while(True):
try:
aadharNumber = eval(input("Aadhar Number: "))
if len(str(aadharNumber)) ==12:
break
else:
print("Your aadhar number must have 12 digits")
except:
print("Enter only number")
print("[Link] Wheeler")
print("[Link] Wheeler")
vehicle = int(input("Enter your details:"))
if age >= 12 and age <= 60:
print("Successfully submitted the application")
else:
print("Your are not eligible for the license")
Output:
License Process
Name : aaa
Blood Group : a
Address : weqqe
Age: 12
Aadhar Number: s
Enter only number
Aadhar Number: 12
Your aadhar number must have 12 digits
Aadhar Number: 123333333333
[Link] Wheeler
[Link] Wheeler
Enter your details:1
Successfully submitted the application
Ex. No. 7 CLASSES AND OBJECTS
Date :
Aim:
Algorithm:
Step 3: Use the init () function to assign values to object properties, or other
operations that are necessary to do when the object is being created.
Step 4: The self parameter is a reference to the current instance of the class, and is
used to access variables that belong to the class.
Program:
Class Student:
Type = 'Student'
def __init (self, id, dpet):
[Link] = id
[Link] = dept
S1= Student(104, "CSE")
S2 = Student(205, "IT")
print('Student 1 details:')
print('Type is :', [Link])
print('ID: ', [Link])
print('Dept: ', [Link])
print('Student 2 details:')
print('Type is:', [Link])
print('ID: ', [Link])
print('Dept: ', [Link])
print("\nAccessing class variable using class name")
print(Student .Type)
Output:
Student 1 details:
Type is Student
ID: 104
Dept: CSE
Student 2 details:
Type is Student
ID: 205
Dept: IT
Ex. No. 8 PACKAGES AND MODULES
Date :
Algorithm:
1. Create my_package folder and create files with .py extension having user
defined modules
2. Add the required modules of the packages in main program file
3. Use modules from the package by calling them
Program:
[Link]
def greet(name):
return f"Hello, {name}! Welcome to Python Packages."
[Link]
Output :
Addition: 8
Multiplication: 24
Ex. No. 9 OOPS CONCEPT - DATA HIDING
Date :
Algorithm:
Program:
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
def get_balance(self):
return self.__balance # Controlled access to balance
account = BankAccount(1000)
✅ Allowed
[Link](500)
Output:
1500
Ex. No. 10 OOPS CONCEPT - DATA ABSTRACTION
Date :
Algorithm:
1. Create a class which has an abstract method by importing ABC package
2. Override the abstract method in inherited classes
3. Create object for inherited classes
4. Call the abstract module for each object
Program:
class Tesla(Car):
def mileage(self):
print("The mileage is 30kmph")
class Suzuki(Car):
def mileage(self):
print("The mileage is 25kmph ")
class Duster(Car):
def mileage(self):
print("The mileage is 24kmph ")
class Renault(Car):
def mileage(self):
print("The mileage is 27kmph ")
t= Tesla ()
[Link]()
r = Renault()
[Link]()
s = Suzuki()
[Link]()
d = Duster()
[Link]()
Output
Aim:
To write a Python program that performs numerical operations using the math
module for mathematical functions and the random module to generate random
numbers.
Algorithm:
Step 2: Generate two random numbers within a specified range (e.g., 1 to 100).
Square root
Power function
Program:
import math
import random
radian = [Link](angle)
Output:
Date :
Aim:
To create user-defined functions with different types of function Arguments
and call them from program.
Algorithm:
1. Define a function which can take any type of argument.
2. Print the values for positional arguments.
3. Print the values for keyword arguments.
4. Print the values for default arguments.
5. Print the values for variable length arguments.
6. Call the function by using different kinds of arguments.
7. Run the program and verify the output.
Program:
def demo_function(a, b, c=10, *args, d=20, **kwargs):
print(f"Positional Arguments: a={a}, b={b}")
print(f"Default Argument: c={c}")
print(f"Variable-Length Positional Arguments (*args): {args}")
print(f"Keyword-Only Argument with Default: d={d}")
# 1. Positional Arguments
print("Example 1: Positional Arguments")
demo_function(1, 2)
Output
Ex. No: 13 CREATING NUMPY ARRAYS FROM PYTHON DATA
STRUCTURES
Date:
Aim:
Algorithm:
import numpy as np
# From a Python list
array_from_list = [Link]([1, 2, 3, 4, 5])
# From a Python tuple
array_from_tuple = [Link]((10, 20, 30))
# From a nested Python list (multi-dimensional array)
array_from_nested_list = [Link]([[1, 2], [3, 4], [5, 6]])
print(array_from_list)
print(array_from_tuple)
print(array_from_nested_list)
# Array of zeros
array_of_zeros = [Link]((3, 3))
# Array of ones
array_of_ones = [Link]((2, 4))
# Array with values within a range
array_arange = [Link](0, 10, 2)
# Array with evenly spaced values
array_linspace = [Link](0, 1, 5)
print(array_of_zeros)
print(array_of_ones)
print(array_arange)
print(array_linspace)
# Random values between 0 and 1
random_array = [Link](3, 3)
# Random integers within a range
random_integers = [Link](0, 10, (2, 4))
# Random values from a normal distribution
random_normal = [Link](3, 3)
print(random_array)
print(random_integers)
print(random_normal)
Output:
[1 2 3 4 5]
[10 20 30]
[[1 2]
[3 4]
[5 6]]
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[0 2 4 6 8]
[0. 0.25 0.5 0.75 1. ]
[[0.753432 0.84873521 0.24197781]
[0.17747662 0.7981542 0.00641123]
[0.43488292 0.36263485 0.90986592]]
[[5 5 3 0]
[7 3 6 5]]
[[ 0.19532656 0.50074958 0.91183389]
[-1.00408449 -1.3168787 -0.01482787]
[ 0.99549621 1.31897228 -2.27609934]]
Ex. No: 14 MANIPULATION OF NUMPY ARRAYS
Date:
Aim
Algorithm
Source Code
import numpy as np
arr = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Original Array:\n", arr)
print("\nElement at row 1, column 2:", arr[1, 2])
print("\nFirst two rows:\n", arr[:2])
print("\nLast two columns:\n", arr[:, -2:])
reshaped_arr = [Link](1, 9)
print("\nReshaped Array (1x9):\n", reshaped_arr)
arr2 = [Link]([[10, 11, 12]])
joined_arr = [Link]((arr, arr2), axis=0) # Join along rows
print("\nJoined Array:\n", joined_arr)
Output
Original Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Joined Array:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Ex. No: 15 CREATING PANDAS SERIES AND DATAFRAME
Date :
Aim:
● Pandas Series: Can be created from lists, dictionaries, etc., and is similar to
a 1D array.
● Pandas DataFrame: Can be created from lists, dictionaries, or NumPy
arrays, and is like a 2D table with rows and columns.
Algorithm:
Source Code:
# Creating a DataFrame from a Series
import pandas as pd
s = [Link]([10, 20, 30, 40, 50])
print(s)
s = [Link]([10, 20, 30, 40, 50], name="Numbers")
print(s)
# Using Multiple Series to create a DataFrame
s1 = [Link]([10, 20, 30, 40, 50], name="Numbers")
s2 = [Link](["apple", "orange", "banana", "grape", "watermelon"],
name="Fruits")
df = [Link]([s1, s2], axis=1)
print(df)
# Adding a new column to an existing DataFrame
df = [Link]({"Numbers": [10, 20, 30, 40, 50], "Fruits": ["apple",
"orange", "banana", "grape", "watermelon"]})
new_col = [Link]([5, 4, 3, 2, 1], name="Ranks")
df = [Link]([df, new_col], axis=1)
print(df)
Output:
0 10
1 20
2 30
3 40
4 50
dtype: int64
0 10
1 20
2 30
3 40
4 50
Numbers Fruits
0 10 apple
1 20 orange
2 30 banana
3 40 grape
4 50 watermelon
Date:
Aim:
Algorithm:
Step 1: Start.
Step 9: Find the count and uniqueness of the given categorical values.
import pandas as pd
# Load the CSV file into a DataFrame
df = pd.read_csv('sample_data.csv') # Replace with your actual file path
Output :
First 5 Records:
ID Name Age City
0 1 Alice 25 New York
1 2 Bob 30 Los Angeles
2 3 Charlie 35 Chicago
3 4 Diana 28 Houston
4 5 Frank 48 Los Angeles
Last 5 Records:
ID Name Age City
5 6 Grace 34 San Diego
6 7 Jack 39 Los Angeles
7 8 Alice 29 Chicago
8 9 Eve 38 Phoenix
9 10 Alice 40 Los Angeles
Output :
Shape: (10, 4)
Index: RangeIndex(start=0, stop=10, step=1)
Columns: Index(['ID', 'Name', 'Age', 'City'], dtype='object')
#C. Select rows where Age > 30
selected_rows = df[df['Age'] > 30]
print("\nRecords where Age > 30:")
print(selected_rows)
Output :
summary = [Link]()
print("\nSummary Statistics:")
print(summary)
Output :
Mean Age: 34.6
Summary Statistics:
ID Age Age Rank
count 10.00000 10.000000 10.00000
mean 5.50000 34.600000 5.50000
std 3.02765 6.899275 3.02765
min 1.00000 25.000000 1.00000
25% 3.25000 29.250000 3.25000
50% 5.50000 34.500000 5.50000
75% 7.75000 38.750000 7.75000
max 10.00000 48.000000 10.00000
unique_cities = df['City'].unique()
print("\nUnique Cities:")
print(unique_cities)
Output :
Unique Cities:
['New York' 'Los Angeles' 'Chicago' 'Houston' 'San Diego' 'Phoenix']
# [Link] columns
df_renamed_single = [Link](columns={'Name': 'Full Name'})
print("\nDataFrame after Renaming 'Name' to 'Full Name':")
print(df_renamed_single)
Output :
DataFrame after Renaming 'Name' to 'Full Name':
ID Full Name Age City Age Rank
0 1 Alice 25 New York 1.0
1 2 Bob 30 Los Angeles 4.0
2 3 Charlie 35 Chicago 6.0
3 4 Diana 28 Houston 2.0
4 5 Frank 48 Los Angeles 10.0
5 6 Grace 34 San Diego 5.0
6 7 Jack 39 Los Angeles 8.0
7 8 Alice 29 Chicago 3.0
8 9 Eve 38 Phoenix 7.0
9 10 Alice 40 Los Angeles 9.0
DataFrame after Renaming Multiple Columns:
Identifier Name Years Old City Age Rank
0 1 Alice 25 New York 1.0
1 2 Bob 30 Los Angeles 4.0
2 3 Charlie 35 Chicago 6.0
3 4 Diana 28 Houston 2.0
4 5 Frank 48 Los Angeles 10.0
5 6 Grace 34 San Diego 5.0
6 7 Jack 39 Los Angeles 8.0
7 8 Alice 29 Chicago 3.0
8 9 Eve 38 Phoenix 7.0
9 10 Alice 40 Los Angeles 9.0
[Link]: 17 DATA CLEANING, PREPARATION AND
VISUALIZATION
DATE:
Aim:
To implement data cleaning, preparation and visualization in python using
pandas.
Algorithm:
Step 1. Read the necessary csv files
Step 2: import in the Python environment with the required libraries installed
(pandas, numpy, matplotlib, seaborn).
Step 3: Include code to handle missing data to detect , fill and remove records
with missing values
Step 4 : Include code to perform data transformation using apply(), map() and
replace methods
Step 5: Include code to Detect and Filter Outliers using Z-transformation
Step 6: Include code to Perform Vectorized String Operations on Pandas Series,
which can handle Null values
Step 7 : Data Visualization is implemented using Line plot, Bar plot, Histogram,
Density plot and Scatter plot with necessary input data.
Step 8 : Check the output for all the operations
Source Code:
# A. Handle Missing Data
import pandas as pd
df=pd.read_csv("[Link]")
print("Original DataFrame:")
print(df)
print([Link]())
# Adding a newrow
#newrow=[111,'xfg','M',None,8765938474,45000]
#[Link][len(df)] = newrow
#print(df)
Output :
Original DataFrame:
Rno Name Gender Age Phone Salary
0 101 aaa M 25.0 2.345678e+09 35000
1 102 bbb F 27.0 5.678938e+09 72000
2 103 ccc M 26.0 6.273458e+09 54000
3 104 ddd M 25.0 7.654938e+09 61000
4 105 eee F 29.0 6.432724e+09 50000
5 106 abc M 26.0 4.563783e+09 62000
6 107 aef F 25.0 6.758493e+09 41000
7 108 srt F NaN 7.658494e+09 33000
8 109 fgh M 25.0 NaN 42000
9 110 yjk M 100.0 5.647383e+09 60000
<class '[Link]'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 6 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Rno 10 non-null int64
1 Name 10 non-null object
2 Gender 10 non-null object
3 Age 9 non-null float64
4 Phone 9 non-null float64
5 Salary 10 non-null int64
dtypes: float64(2), int64(2), object(2)
memory usage: 612.0+ bytes
None
#replace a value
df['Name'] = df['Name'].replace('aaa', 'AAA')
Output :
df = [Link]({'Age': [10, 12, 12, 13, 12, 11, 100]}) # 100 is an outlier
z_scores = [Link]([Link](df['Age']))
#z_scores = (df[‘Age’] - df['Age'].mean()) / df['Age'].std() # Can apply the formula
directly
threshold = 2
outliers = [Link](z_scores > threshold)
print(z_scores)
print("Outliers at positions:", outliers)
Output :
String Capitalized
0 Peter
1 Paul
2 Mary
3 Guido
dtype: object
String Length
0 5
1 4
2 4
3 5
dtype: int64
# E. Visualize Data
# LINE PLOT:
import pandas as pd
import [Link] as plt
data = {'Year': [2000, 2001, 2002, 2003],'Unemployment Rate': [4.0, 4.7, 5.8, 6.0]}
df = [Link](data)
# Plotting a line chart
[Link](x='Year', y='Unemployment Rate', kind='line')
[Link]()
# BAR PLOT:
df=pd.read_csv(‘[Link]’)
ax = [Link](kind='bar',
x='name',
y='physics_marks',
color='green',
title='BarPlot')
# Customize axis labels (optional, but can be added via 'ax' for more control)
ax.set_xlabel('Name')
ax.set_ylabel('Physics Marks')
Output :
# HISTOGRAM:
import pandas as pd
values = [Link]({
'Length': [2.7, 8.7, 3.4, 2.4, 1.9],
'Breadth': [4.24, 2.67, 7.6, 7.1, 4.9]
})
hist = [Link](bins=5)
[Link]()
Output :
DENSITY PLOT
import pandas as pd
import seaborn as sns
import [Link] as plt
# loading the dataset from seaborn library
data = sns.load_dataset('car_crashes')
# plotting the density plot for 'speeding' attribute using [Link]()
[Link](color='green')
[Link]('Density plot for Speeding')
[Link]()
# viewing the dataset
print([Link](4))
Output :
# SCATTER PLOT
ax.set_ylabel("Physics Marks")
[Link]()
Output :