LABORATORY MANUALjinay

You might also like

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

LABORATORY MANUAL

PYTHON FOR DATA SCIENCE

SUBJECT CODE: 3150713


INFORMATION AND COMMUNICATION TECHNOLOGY
DEPARTMENT

B.E. 5TH SEMESTER

Name: Jinay Sodha

Enrolment number: 201310132129

Batch: ICT B4

Year:2020-2024

Adani Institute of Infrastructure Engineering (AIIE)


Shantigram Township
Nr Vaishnodevi Circle, SG Highway
Ahmedabad 382 421
Gujarat, India
TASK Name of Experiment Marks/ Grades Signature
No.

1
I I. Write a Python program
to print even numbers up to N
using “for” loop. The program
should ask the user to enter the
value of N.
II II. Write a Python program
to print multiplication table of a
given number using “while” loop.
III III. Write a Python program
to calculate grade of a student
based on marks scored in four
subjects.
IV IV. Write a Python
program to read text and count total
number of lower case letters, upper
case letters, digits, alphabets,
special characters, and total words.
V V. Write a Python program
to create a list. Ask the user for
numbers, and keep adding them to
the list, till the user wishes to
continue.

2.
I I. Write a Python program
to get the maximum and minimum
value in a dictionary.
II II. Write a Python program
to combine two dictionary adding
values for common keys.
III III. Write a Python program
to create a dictionary from a string.
Note: Track the count of the letters
from the string.
IV IV. Write a Python
program to create two sets by using
“add” method. Find out the union,
intersection, difference, and
symmetric difference of the two
sets. Also compare the sets. Show
test cases involving number as well
as string items in the sets.
V V. Write a Python function
to check whether a number is
perfect or not.
3.
I I. Write a Python function
that takes a list and returns a new
list with unique elements of the
first list.
II II. Use Python lambda
functions to create a Python
function that convert any binary
number entered by a user into a
decimal number.
III III. Write a Python program
to check the validity of password
input by users.
IV IV. Write a Python
program to construct the following
pattern, using a nested loop
number.
V V. Create a Time class and
initialize it with hours and minutes:

As Given.
4.
I I. Write a NumPy program
to calculate the difference between
neighboring elements, elementwise
of a given array.
II II. Write a Python program
to multiply two user defined
matrices (size= n*n, where n>2)
using NumPy
III. Write a Python program to
transpose and determinant of a
user-defined matrix (entered as a
3*3 array) using NumPy.
Additionally, find whether the
matrix is invertible. If it is
invertible, also find the inverse of
that matrix.
IV. Solve a system of 3 linear
equations (in 3 variables: x, y, z)
using Python NumPy package.
V. Write a NumPy program to
create a 5x5 array with random
values and find the minimum and
maximum values.

5.
I I. Create a sample
DataFrame as follows.
II II. Write a Pandas program
to select the specified columns and
rows from a given DataFrame.
Select 'name' and 'score' columns in
rows 1, 3, 5, 6 from the following
data frame.
III III. Write a Pandas program
to sort the data frame first by
'name' in descending order, then by
'score' in ascending order.
IV IV. Write a Pandas
program to delete the 'attempts'
column from the DataFrame.
V V. Write a Pandas program
to insert a new column in existing
DataFrame.
VI VI. Write a Pandas
program to select the rows where
the score is missing, i.e. is NaN.
VII VII. Write a Pandas
program to change the score in row
'd' to 11.5.
VIII VIII. Write a Pandas
program to calculate the sum of the
examination attempts by the
students.

6.
I. Create a LabTask6_1.txt file with
atleast 10 lines. (a) Stream the data
in the file using Python.
(b) Sample odd number lines from
the the .txt file.
(c) Randomly sample 30% lines
from the .txt file using Python.
(d) Read the .txt file using pandas
for parsing

II. Create or download any .csv


(Comma Separated Value) from the
publicly available datasets. (a)
Read the .csv using pandas for
parsing.
(b) Display any two columns from
the .csv file
(c) Display any two records (rows)
from the .csv file

III. Create or download any.xls file


from the publicly available datasets
with at least 3 worksheets. Using
pandas in Python for parsing, (a)
read sheet2 from .xls and display it.

(b) read specific columns from a


given excel file
(c) add a column named "column1"
in the third position of the .xls file
(in sheet2) and fill it with NaN
values.
IV. Display any image from an
online source using skimage in
Python. (a) Display the original
image
(b) Display the image in gray scale
(c) Find the shape and type of the
image
(d) Display a cropped version of
the image

(e) Display a resized version of the


image
7.
I I. Write a python program
to read the data from XML file
using pandas library. 2. Write a
Pandas program to extract year,
month, day, hour, minute, second
and weekday from unidentified
flying object (UFO) reporting date
(http://bit.ly/uforeports).
II II. Write a python program
to read data from a text file using
pandas library.
III III. Write a python program
to read data from CSV files using
pandas.
IV IV. 5. Write a simple
python program that draws a line
graph where x = [1,2,3,4] and y =
[1,4,9,16] and gives both axis label
as “X-axis”and “Y-axis”

8.
I I. List the features of
matplotlib.
II II. Write a Python
programming to create a pie chart
with a title of the popularity of
programming Languages. Sample
data: Programming languages:
Java, Python, PHP, JavaScript, C#,
C++ Popularity: 22.2, 17.6, 8.8, 8,
7.7, 6.7
III III. Find the kurtosis and
skewness of a set of numerical
values using Python scipy library.
IV IV. \Write a Python
program to find the quartile of a set
of numerical values at 35
percentile, 60 percentile, and 80
percentile

9.
I I. (a)Write a Pandas
program to drop the columns where
at least one element is missing in a
given DataFrame. (b) Write a
Pandas program to drop the rows
where all elements are missing in a
given DataFrame.
II II. Write a Pandas program
to create a heatmap for more
information about the distribution
of missing values in a given
DataFrame.
III III. Write a Python program
to explain box plot.
IV IV. Write a Python
program to explain histogram.
V V. a) Write a Python
function to find standard deviation
of a set of numbers. b) Read any
numerical column from a .csv file
and find its standard deviation
using the defined function in 8.
VI VI. Draw the following
undirected graph using networkx
library
Practical 1
Aim:
Write a Python program to print even numbers up to N using the “for” loop. The program
should ask the user to enter the value of N.
Input:

maximum = int(input(" Please Enter the Maximum Value : "))

for number in range(1, maximum+1):


if(number % 2 == 0):
print("{0}".format(number))

OUTPUT:

Aim: Write a Python program to print the multiplication table of a given number using the
“while” loop.
Input:
number = int(input ("Enter the number of which the user wants to print the multiplication
table: "))

print ("The Multiplication Table of: ", number)


for count in range(1, 11):
print (number, 'x', count, '=', number * count)

OUTPUT:
Aim: Write a Python program to calculate grade of a student based on marks scored in four
subjects.
The program should first ask the user to enter the student's name, followed by marks in four
subjects. The grade evaluation should be as follows :
If the percentage >= 90, then the student should be given A grade.
If 90 > percentage >= 60, then student should be given B grade.
If 60 > percentage >= 45, then student should be given C grade.
If 45 > percentage >= 33, then student should be given D grade.
If 33 > percentage, then the student should be given E grade.
The final output should display: “Hey $$NAME$$, You scored $$GRADE$$ grade.
Input:
name:chr(input("enter your name:"))
sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=60&avg<90):
print("Grade: B")
elif(avg>=45&avg<60):
print("Grade: C")
elif(avg>=33&avg<45):
print("Grade: D")
else:
print("Grade: F")

OUTPUT:
Aim: Write a Python program to read the text and count the total number of lower case letters,
upper case letters, digits, alphabets, special characters, and total words.
Input:
def check_input(string):
lower = 0
upper = 0
special_list = ["!","~","#","@","%","&","/","*","-","+","_"]
special = 0
digit = 0
alphabet = 0
total = 0
for i in range(len(string)):
if string[i].isupper():
upper += 1
elif string[i].islower():
lower += 1
elif string[i] in special_list:
special += 1
elif string[i] in range(0,10):
digit += 1
else:
pass
print("Lower Case Latters : ", lower)

print("Upper Case Latters : ", upper)


print("Digits : ", digit)
print("Alphabets : ", lower+upper)
print("Special Characters : ", special)
print("Total Words : ", lower+upper+digit+special)
enterString = input("Enter a String :")
check_input(enterString)
Output:

Aim: Write a Python program to create a list. Ask the user for numbers, and keep adding them to
the list, till the user wishes to continue.
a) Write the code which finds and displays the largest number from the list
b) Write the code which searches a number (user-entered) in the list using linear search
Input:
lst=[]

n= int(input("enter number of element :"))


for i in range(0,n):
ele=int(input())

lst.append(ele)
print(lst)

lst.sort()
print("largest element is:",lst[-1])

OUTPUT:
Practical 2

Aim: Write a Python program to get the maximum and minimum values in a dictionary.
Input:
dict = {"Salary1":"2000","Salary2":"30000","Salary3":"50000"}
print("Max Number :",max(dict.values()))
print("Min Number :",min(dict.values()))
Output:

Aim:
Write a Python program to combine two dictionaries adding values for common keys.
Input:
def Merge(dict1, dict2):
for i in dict2.keys():
dict1[i]=dict2[i]
return dict1
d1 = {"name":"Yagnik","mail":"00yagnik@gmail.com", "marks":77}
d2 = {"branch":"ICT","marks":33, "clg":"Adani"}
for i,j in d1.items():
for x,y in d2.items():
if i == x :
d2[i] = (j+y)
d3 = Merge(d1,d2)
print(d3)
#Alternative Approch
for key in d2:
if key in d1:
d2[key] = d2[key]+ d1[key]
print(d2)
Output:

Aim: Write a Python program to create a dictionary from a string. Note: Track the count of the
letters from the string.
Input:
s = input("Enter String :")
d = {}
for x in s:
d[x] = d.get(x, 0) + 1
print(d)
Output:
Aim: Write a Python program to create two sets by using the “add” method. Find out the union,
intersection, difference, and symmetric difference of the two sets. Also, compare the sets. Show
test cases involving numbers as well as string items in the sets.
Input:
set = {1,2,3,4,5}
print(set)
# Union
set2 = {6,5,7}
print(set | set2)
# Diffrence
print(set - set2)
# intersection
print(set & set2)
# symmetric diff
print(set ^ set2)
# add
set.add(6)
set.add(7)
print("Set After Adding 6 and 7 is : ",set)
Output:

Aim: Write a Python function to check whether a number is perfect or not.


Input:
num = int(input("Enter a Number : "))
sum = 0
for x in range (1,num):
if num%x == 0:
sum = sum + x
if sum == num:
print("This is Perfect Number")
else:
print("This is Not Perfect Number")
Output:
Practical 3
Aim: Write a Python function that takes a list and returns a new list with unique elements of the
first list.
Input:
list1 = []
n = int(input("How Many Inputs Wants to Enter : "))
for x in range(n):
y = input("Enter Number:\n")
list1.append(y)
def unique_list(l):
new_list = []
for x in l:
if x not in new_list:
new_list.append(x)
return new_list
ans = unique_list(list1)
print(ans)
Output:

Aim: Use Python lambda functions to create a Python function that convert any binary number
entered by a user into a decimal number
Input:
b = input("What Binary number would you like to convert into Decimal? \n")
convert= lambda b: str(int(b, 2))
print(b + " is " + convert(b) + " in Decimal")
Output:
Aim: Write a Python program to check the validity of password input by users.
Validation: At least 1 letter between [a-z] and 1 letter between [A-Z].
At least 1 number between [0-9].
At least 1 character from [$#@].
Minimum length 6 characters.
Maximum length 16 characters.
Input:
while True:
password = input("Enter Your Password : ")
char_a = 0
char_A = 0
special = 0
number = 0
maximum = 0
minimum = 0
again = 0
for i in password:
if (i>='a' and i<='z') or (i>='A' and i<='Z'):
if i>='a' and i<='z':
char_a = char_a + 1
elif i>='A' and i<='Z':
char_A = char_A + 1
elif i>='0' and i<='9':
number = number + 1
elif len(password) < 6:
minimum = minimum + 1
elif len(password) >16:
maximum = maximum +1
else:
special = special + 1
if char_A == 0:
print("Password Must Have At Least One Uppercase!!\n")
again = again + 1
elif char_a == 0:
print("Password Must Have At Least One Lowercase!!\n")
again = again + 1
elif number == 0:
print("Password Must Have At Least One Number!!\n")
again = again + 1
elif maximum > 0:
print("Maximum Password Length is 16char!!\n")
again = again + 1
elif minimum > 0:
print("Minimum Password Length is 6char!!\n")
again = again + 1
elif special == 0:
print("Password Must Have At Least One Special Character!!\n")
again = again + 1
if again > 0:
print("Please Enter Password Again Carefully!!\n")
else:
print("Enterred Password is Valid!!\n")
break
Output:

Aim: Write a Python program to construct the following pattern, using a nested loop number.
1
22
333
4444
55555
666666
7777777
88888888
999999999

Input:
for x in range(1,10):
for y in range(1,x+1):
print(x,end="")
print("")

Output:
Aim: Create a Time class and initialize it with hours and minutes. a) Make a method addTime
which should take two-time objects and add them. E.g.- (2 hour and 50 min)+(1 hr and 20 min)
is (4 hr and 10 min) b) Make a method displayTime which should print the time. c) Make a
method DisplayMinute which should display the total minutes in the Time. E.g.- (1 hr 2 min)
should display 62 minute
Input:
class Time():
def __init__(self, hours, mins):
self.hours = hours
self.mins = mins
def addTime(t1, t2):
t3 = Time(0,0)
if t1.mins+t2.mins > 60:
t3.hours = (t1.mins+t2.mins)//60
t3.hours = t3.hours+t1.hours+t2.hours
t3.mins = (t1.mins + t2.mins) % 60
return t3
def displayTime(self):
print ("Time is",self.hours,"hours and",self.mins,"minutes.")
def displayMinute(self):
print ((self.hours*60)+self.mins)
print("Enter Hours and Minutes for Time 1")
a = int(input("Hours : "))
b = int(input("Minutes : "))
print("Enter Hours and Minutes for Time 2")
c = int(input("Hours : "))
d = int(input("Minutes : "))
A = Time(a, b)
B = Time(c, d)
c = Time.addTime(A,B)
c.displayTime()
c.displayMinute()
Output:
Practical 4

Aim: Write a NumPy program to calculate the difference between neighboring elements,
element-wise of a given array.
Input:
import numpy as np
x = np.array([7,5,3,9,6])
print("Original Array: ")
print(x)
print("Difference between neighboring elements, element-wise of the said array.")
print(np.diff(x))
Output:

Aim:
Write a Python program to multiply two user defined matrices (size= n*n, where n>2)
using NumPy.
Input:
import numpy as np
a = [[1,2],[3,4]]
b = [[5,6],[7,8]]
c = np.dot(a,b)
#c=a@b
print(c)
Output:

Aim: Write a Python program to transpose and determinant of a user-defined matrix (entered as
a 3*3 array) using NumPy. Additionally, find whether the matrix is invertible. If it is invertible,
also find the inverse of that matrix.
Input:
mport numpy as np
arr = np.array([[1,2,3],[4,5,5],[8,8,9]])
print(arr,"\n")
print(np.transpose(arr),"\n")
det = np.linalg.det(arr)
print(det,"\n")
if int(det) != 0:
inv = np.linalg.inv(arr)
print(inv,"\n")
else:
print("Determinant does not exits!!")
Output:
Aim: Solve a system of 3 linear equations (in 3 variables: x, y, z) using Python NumPy package.
Input:
# Example - 8x+3y−z=10
# −4x+5y+5z=17
# 3x+6y−12z=31
import numpy as np
eq = np.array([[8,3,-1],[-4,5,5],[3,6,-12]])
ans = np.array([10,17,31])
# res = np.linalg.solve(eq,ans) #Alternative Way
res = np.linalg.inv(eq).dot(ans)
print(res)
Output:

Aim: Write a NumPy program to create a 5x5 array with random values and find the minimum
and maximum values.
Input:
import numpy as np
x = np.random.random((5,5))
print("Original Array:")
print(x,"\n")
xmin, xmax = x.min(), x.max()
print("Minimum and Maximum Values:")
print(xmin, xmax)
Output:
Practical 5
Aim: Write a program to create a dataframe "student_data" using pandas with the
following details; provide at least 10 sample data and display the same.
Student name, enrollment number, date of birth, city, CPI
Input:
import pandas as pdimport
numpy as np

student_data = {'Student name': ['Sourav', 'Suman', 'Ashis', 'Nayan', 'Nisha', 'Shilpa','Pratip', 'Sagar',
'Rahul', 'Jasmin'],
'enrollment number': [32154484, 32154485, 32154486, 32154487, 32154488,
32154489, 32154490, 32154491, 32154492, 32154493],
'date of birth': ['21 Oct 1999', '11 Mar 1998', '17 Jun 1999', '10 Jan 2000',
'15 Aug 1999', '20 Jun 1998', '23 Jul 1998', '07 Feb 1999', '13 May 1999', '28 Mar 1999'],
'city': ['Bangalore', 'Srinagar', 'Rajkot', 'Ranchi', 'Agra', 'Nasik','Raipur', 'Goa',
'Patna', 'Rajkot'],
'CPI': [8.77, 9.5, 7.98, 8.33, 8.21, 8.88, 8.64, 9.91, 8.87, 8.65]}

student_data_frame = pd.DataFrame(student_data)
print(student_data_frame)

Output:
Aim-5(b): Write a program to select and display student names and CPI columns from
"student_data".
Input:
import pandas as pd
import numpy as np
student_data = {'Student name':['Sourav','Suman','Ashis','Nayan','Nisha','Shilpa','Pratip','Sagar','Rahul','Jasmin'] ,
'enrollment
number':[32154484,32154485,32154486,32154487,32154488,32154489,32154490,32154491,32154492,321
54493] ,
'date of birth': ['21 Oct 1999','11 Mar 1998','17 Jun 1999','10 Jan 2000','15
Aug 1999','20 Jun 1998','23 Jul 1998','07 Feb 1999','13 May 1999','28 Mar 1999'],
'city': ['Bangalore','Srinagar','Rajkot','Ranchi','Agra','Nasik','Raipur','Goa','Patna','Rajkot'],
'CPI': [8.77,9.5,7.98,8.33,8.21,8.88,8.64,9.91,8.87,8.65]}

student_data_frame = pd.DataFrame(student_data)

print(student_data_frame[['Student name', 'CPI']])

Output:
Aim: Write a program to sort "student_data" using CPI column in descending order;
further, sort the same using student name column in ascending order and display it.
Input:

import pandas as pdimport


numpy as np

student_data = {'Student name':['Sourav','Suman','Ashis','Nayan','Nisha','Shilpa','Pratip','Sagar','Rahul','Jasmin'] ,


'enrollment
number':[32154484,32154485,32154486,32154487,32154488,32154489,32154490,32154491,32154492,321
54493] ,
'date of birth': ['21 Oct 1999','11 Mar 1998','17 Jun 1999','10 Jan 2000','15
Aug 1999','20 Jun 1998','23 Jul 1998','07 Feb 1999','13 May 1999','28 Mar 1999'],
'city': ['Bangalore','Srinagar','Rajkot','Ranchi','Agra','Nasik','Raipur','Goa','Patna','Rajkot'],
'CPI': [8.77,9.5,7.98,8.33,8.21,8.88,8.64,9.91,8.87,8.65]}

student_data_frame = pd.DataFrame(student_data)

desc_cpi = student_data_frame.sort_values('CPI', ascending = False)


print(desc_cpi)
print("\n")

asc_name = student_data_frame.sort_values('Student name')


print(asc_name)

Output:
Aim: Write a program to delete city column from "student_data" and display the
remaining dataframe.
Input:

import pandas as pdimport


numpy as np

student_data = {'Student name':['Sourav','Suman','Ashis','Nayan','Nisha','Shilpa','Pratip','Sagar','Rahul','Jasmin'] ,


'enrollment
number':[32154484,32154485,32154486,32154487,32154488,32154489,32154490,32154491,32154492,321
54493] ,
'date of birth': ['21 Oct 1999','11 Mar 1998','17 Jun 1999','10 Jan 2000','15
Aug 1999','20 Jun 1998','23 Jul 1998','07 Feb 1999','13 May 1999','28 Mar 1999'],
'city': ['Bangalore','Srinagar','Rajkot','Ranchi','Agra','Nasik','Raipur','Goa','Patna','Rajkot'],
'CPI': [8.77,9.5,7.98,8.33,8.21,8.88,8.64,9.91,8.87,8.65]}

student_data_frame = pd.DataFrame(student_data)
student_data_frame.drop('city', axis = 1, inplace = True)
print(student_data_frame)

Output:
Aim: Write a program to insert a new column.
Input:
import pandas as pdimport
numpy as np

student_data = {'Student name':['Sourav','Suman','Ashis','Nayan','Nisha','Shilpa','Pratip','Sagar','Rahul','Jasmin'] ,


'enrollment
number':[32154484,32154485,32154486,32154487,32154488,32154489,32154490,32154491,32154492,321
54493] ,
'date of birth': ['21 Oct 1999','11 Mar 1998','17 Jun 1999','10 Jan 2000','15
Aug 1999','20 Jun 1998','23 Jul 1998','07 Feb 1999','13 May 1999','28 Mar 1999'],
'city': ['Bangalore','Srinagar','Rajkot','Ranchi','Agra','Nasik','Raipur','Goa','Patna','Rajkot'],
'CPI': [8.77,9.5,7.98,8.33,8.21,8.88,8.64,9.91,8.87,8.65]}

student_data_frame = pd.DataFrame(student_data)
fav_sub = ['PYD', 'ADA', 'ADA', 'OOPJ', 'PYD', 'PYD', 'PYD', 'ADA', 'OOPJ', 'OOPJ']
student_data_frame['fav_sub'] = fav_sub
print(student_data_frame)

Output:

You might also like