Python Lab Manual
Python Lab Manual
LAB MANUAL
1
Python Lab Manual
Index
2
Python Lab Manual
Exercise 1
Integer=5
Float=78.9
String='Suchetha'
Tuple=(45,78,32.8,'Suchetha')
List=[45,90,'Hello']
Set={78,89,67}
print(type(Integer))
print(type(Float))
print(type(String))
print(type(Tuple)) print(type(List))
print(type(Set))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'tuple'>
<class 'list'>
<class 'set'>
A=1653
B=7863
#Arthematic operators
print("ARTHEMATIC OPERATORS")
print("Addition:",A+B)#Addition
print("Subraction:",A-B)#Subtraction
print("Multiplication:",A*B)#Multiplication
print("Float division:",A/B)#Division(float)
print("Integer division:",A//B)#Division(int)
print("Remaider:",A%B)#Modulus
3
Python Lab Manual
print("Power:",A**B)#Exponentiation
print("\nASSIGNMENT OPERATORS")
#Assignment operators
X=542647
print("X is :",X)
X+=3 #X=X+3
print("X is :",X)
X-=3 #X=X-3
print("X is :",X)
X*=3 #X=X*
print("X is :",X)
X//=3 #X=X//3
print("X is :",X)
X%=3 #X=X%3
print("X is :",X)
X**=3 #X=X**3
print("X is :",X)
X&=3 #X=X&3
print("X is :",X)
X|=3 #X=X|3
print("X is :",X)
X^=3 #X=X^3
print("X is :",X)
X<<=3 #X=X<<3
print("X is :",X)
X>>=3 #X=X>>3
print("X is :",X)
X/=3 #X=X/3
print("X is :",X)
#Comparison operators
print("\nCOMPARISON OPERATORS")
print("A==B: ",A==B)
print("A!=B: ",A!=B)
print("A<B: ",A<B)
print("A>B: ",A>B)
print("A<=B: ",A<=B)
print("A>=B: ",A>=B)
#Logical operators
print("\nLOGICAL OPERATORS")
print("A>10 and B<10: ",A>10 and
B<10) print("A>10 or B<10: ",A>10
or B<10)
print("not(A>10 and B<10): ",not(A>10 and B<10))
#Membership operators
print("\nMEMBERSHIP OPERATIONS")
4
Python Lab Manual
L=["Apple","Mango"]
print("Pineapple is there in L:","Pineapple" in L)#in
print("Pineapple is not there in L:","Pineapple" not in L)#not in
print("Mango is there in L:","Mango" in L)#in
print("Mango is not there in L:","Mango" not in L)#not in
#Identity operators
print("\nIDENTITY OPERATORS")
print("A is B: ",A is B)#is-checks if both are same
print("A is not B: ",A is not B)#is not-checks if both not are same
#Bitwise operators
print("\nBITWISE OPERATORS")
print("And:",A&B)#And
print("Or:",A|B)#Or
print("Binary left shift:",A<<2)#Binary Left shift by 2
print("Binary right shift:",B>>2)#Binary Right shift
by 2 print("Binary Xor:",A^B)#Binary Xor
print("Binary one's complement:",~A)#Binary one's complement(NOT)
OutPut:
ARTHEMATIC OPERATORS
Addition: 9516
Subraction: -6210
Multiplication: 12997539
Float division: 0.2102251049217856
Integer division: 0
Remaider: 1653
Power:190303875322563709653989761043708948896755897273709912141338919820843374057302736273715
ASSIGNMENT OPERATORS
X is : 542647
X is : 542650
X is : 542647
X is : 1627941
X is : 542647
X is : 1
X is : 1
X is : 1
X is : 3
X is : 0
X is : 0
X is : 0
X is : 0.0
COMPARISON OPERATORS
A==B: False A!
=B: True A<B:
True
A>B:False
A<=B:True A>=B:
False
LOGICAL OPERATORS
5
Python Lab Manual
A>10 and B<10: False A>10
or B<10: True
not(A>10 and B<10): True
MEMBERSHIP OPERATIONS
Pineapple is there in L: False
Pineapple is not there in L: True
Mango is there in L: True
Mango is not there in L: False
IDENTITY OPERATORS
A is B: False
A is not B: True
BITWISE OPERATORS
And: 1589
Or: 7927
Binary left shift: 6612
Binary right shift: 1965
Binary Xor: 6338
Binary one's complement: -1654
Enter integer a:
21
Enter integer b:
11
Sum of a+b: 32
6
Python Lab Manual
Enter integer a:
11
Enter integer b:
12
Sum of a+b: 23
Enter integer a:
90
Enter integer b:
21
sum of a+b: 111
Exercise 2
7
Python Lab Manual
print(dir(random))
[' call ', ' class ', ' delattr ', ' dir ', ' doc ', ' eq ', ' format ', '
ge
# module math
import math
from math import pi,sqrt,
factorial print(math.pi)
print(sqrt(16))
print(factorial(6))
3.141592653589793
4.0
720
2.718281828459045
3.141592653589793
8
Python Lab Manual
10
Python Lab Manual
Cachetools intervaltree pyemd Wheel
caffe2 io pyexpat widgetsnbextension
Calendar ipaddress pyglet Wordcloud
Catalogue ipykernel pygments Wrapt
Certify ipykernel_launcher pygtkcompat Wsgiref
Cffi ipython_genutils pylab Xarray
Cftime ipywidgets pymc3 Xdrlib
Cgi isympy pymeeus Xgboost
Cgitb itertools pymongo Xkit
Chardet itsdangerous pymystem3 Xlrd
charset_normalizer jax pynvml Xlwt
Chess jaxlib pyparsing Xml
Chunk jdcal pyrsistent Xmlrpc
Click jedi pysndfile Xxlimited
Client jieba pystan Xxsubtype
Cloudpickle jinja2 pytest Yaml
Cmake joblib python_utils Yellowbrick
Cmath jpeg4py pytz Zict
Cmd json pyviz_comms Zipapp
Cmdstanpy jsonschema pywt Zipfile
Code jupyter pyximport Zipimport
Codecs jupyter_client qdldl Zipp
Codeop jupyter_console qtconsole Zlib
Colab jupyter_core qtpy Zmq
Collections jupyterlab_pygments queue
Colorcet jupyterlab_widgets quopri
Enter any module name to get more help. Or, type "modules spam" to search for modules whose name or summary contain the
string "spam".
#build in functions
print("Hello world")
print(int(8.0))
print(float(8))
print(complex(8))
a=input(int())
Hello
world 8
8.0
(8+0j)
67
11
Python Lab Manual
Exercise 3
#i)List
List = []
print("Blank List: ")
print(List)
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
List = ["Car", "Cat", "Fish"] print("\nList
Items: ")
print(List[0])
print(List[2])
OUTPUT:
Blank List:[]
List of numbers:
[10, 20, 14]
List Items:
Car Fish
Multi-Dimensional List:
[['Car', 'Cat'], ['Fish']]
#ii)Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
Tuple1 = ('Hello', 'World')
print("\nTuple with the use of String: ")
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
Tuple1 = tuple('Hello')
print("\nTuple with the use of function: ")
print(Tuple1)
OUTPUT:
12
Python Lab Manual
Initial empty Tuple:()
Tuple with the use of function: ('H', 'e', 'l', 'l', 'o')
#iii)Dictionary
Dict = dict({1: 'Nathan', 2: 'James', 3:'USA'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Dict = dict([(1, 'Lap'), (2, 'Top')])
print("\nDictionary with each item as a pair: ")
print(Dict)
print("\nDict keys:",list(Dict.keys()))
values=Dict.values
print("\nDict values:",list(Dict.values()))
OUTPUT:
Dictionary with the use of dict():{1: 'Nathan', 2: 'James', 3: 'USA'}
#Strings
String1 = 'Messi is a Football Player'
print("String with the use of Single Quotes: ")
print(String1)
String1 = "Sun rises in the east"
print("\nString with the use of Double Quotes: ")
print(String1)
String1 = '''Captain Chandler is on the board"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
String1 = '''Live to Rule'''
print("\nCreating a multiline String: ")
print(String1)
OUTPUT:
String with the use of Single Quotes: Messi is a Football Player
String with the use of Double Quotes: Sun rises in the east
13
Python Lab Manual
String with the use of Triple Quotes: Captain Chandler is on the board"
Creating a multiline String:Live to Rule
#String operations
#Accessing characters in string:
String1 = "Everything is OKay"
print("Initial String: ")
print(String1)
print("\nFirst character of String is: ")
print(String1[0])
print("\nLast character of String is: ")
print(String1[-1])
OUTPUT:
Initial String:
Everything is OKay
First character of String is: E
Last character of String is:y
#String Slicing:
String1 = "There is a key"
print("Initial String: ")
print(String1)
print("\nSlicing characters from 3-12: ")
print(String1[3:12])
print("\nSlicing characters between " +"3rd and 2nd last character: ")
print(String1[3:-2])
OUTPUT:
Initial String:
There is a key
OUTPUT:
Initial String:
Hello, This is Suchetha
14
Python Lab Manual
Deleting entire String:
#Updating :
String1 = "As much as U can"
print("Initial String: ")
print(String1)
String1 = "The more we can" print("\
nUpdated String: ") print(String1)
OUTPUT:
Initial String:
As much as U can
Updated String:
The more we can
#Formatting of String:
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)
String1 = "{0:.2f}".format(1/6) print("\
none-sixth is : ")
print(String1)
OUTPUT:
Exponent representation of 165.6458
is 1.656458e+02
one-sixth is :0.17
#Regularexpressions
#\A :import re
txt = "The rain in Spain"
#Check if the string starts with "The"
x = re.findall("\AThe", txt)
print(x)
15
Python Lab Manual
if x:
print("Yes, there is a match!")
else:
print("No match")
OUTPUT:
['The']
Yes, there is a match!
#\b :
import re
txt = "The rain in Spain"
#Check if "ain" is present at the beginning of a WORD:
x = re.findall(r"\bain", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
OUTPUT:
[]
No match
#\B:
import re
txt = "The rain in Spain"
OUTPUT:
['ain', 'ain']
Yes, there is at least one match!
#\d:
import re
txt = "The rain in Spain"
#Check if the string contains any digits (numbers from 0-9):
x = re.findall("\d", txt) print(x)
if x:
print("Yes, there are digits")
else:
print("No digits")
16
Python Lab Manual
OUTPUT:
[]
No digits
#\D:
import re
txt = "The rain in Spain"
#Return a match at every no-digit character:
x = re.findall("\D", txt)
print(x)
if x:
print("Yes, there is no digit match!")
else:
print("Yes are are digits")
OUTPUT:
['T', 'h', 'e', ' ', 'r', 'a', 'i', 'n', ' ', 'i', 'n', ' ', 'S', 'p', 'a', 'i', 'n']
Yes, there is no digit match!
#\s:
import re
txt = "The rain in Spain"
#Return a match at every white-space
character: x = re.findall("\s", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
OUTPUT:
[' ', ' ', ' ']
Yes, there is at least one match!
#\t:
import re
txt = "The rain in Spain"
#Return a match at every NON white-space character:
x = re.findall("\S", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
OUTPUT:
['T', 'h', 'e', 'r', 'a', 'i', 'n', 'i', 'n', 'S', 'p', 'a', 'i', 'n']
Yes, there is at least one match!
#\w:
17
Python Lab Manual
import re
txt = "The rain in Spain"
#Return a match at every word character (characters from a to Z, digits from 0-9, and the
underscore
x = re.findall("\w", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
OUTPUT:
['T', 'h', 'e', 'r', 'a', 'i', 'n', 'i', 'n', 'S', 'p', 'a', 'i', 'n']
Yes, there is at least one match!
#\W:
import re
txt = "The rain in Spain"
#Return a match at every NON word character (characters NOT between a and Z. Like "!", "?" white-
spa
x = re.findall("\W", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
OUTPUT:
[' ', ' ', ' ']
Yes, there is at least one match!
#\Z:
import re
txt = "The rain in Spain"
#Check if the string ends with "Spain"
: x = re.findall("Spain\Z", txt)
print(x)
if x:
print("Yes, there is a match!")
else:
print("No match")
OUTPUT:
['Spain']
#[ ] :
import re
txt = "The rain in Spain"
18
Python Lab Manual
#Find all lower case characters alphabetically between "a" and "m"
: x = re.findall("[a-m]", txt)
print(x)
OUTPUT
#\ :
import re
txt = "That will be 59 dollars"
#Find all digit characters:
x = re.findall("\d", txt) print(x)
OUTPUT:
['5', '9']
#. :
import re
txt = "hello world"
#Search for a sequence that starts with "he", followed by two (any) characters, and an "o"
: x = re.findall("he..o", txt)
print(x)
OUTPUT:
['hello']
#^ :
import re
txt = "hello world"
#Check if the string starts with
'hello': x = re.findall("^hello", txt)
if x:
print("Yes, the string starts with 'hello'")
else:
print("No match")
OUTPUT:
#$ :
import re
txt = "hello world"
#Check if the string ends with 'world'
: x = re.findall("world$", txt)
if x:
print("Yes, the string ends with 'world'") else:
print("No match")
19
Python Lab Manual
OUTPUT:
Yes, the string ends with 'world'
#*:
import re
txt = "The rain in Spain falls mainly in the plain!"
#Check if the string contains "ai" followed by 0 or more "x" characters
: x = re.findall("aix*", txt)
print(x) if
x:
print("Yes, there is at least one match!")
else:
print("No match")
OUTPUT:
#+ :
import re
txt = "The rain in Spain falls mainly in the plain!"
#Check if the string contains "ai" followed by 1 or more "n" characters
: x = re.findall("ain+", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
OUTPUT:
['ain', 'ain', 'ain', 'ain']
Yes, there is at least one match!
#{} :
import re
txt = "The rain in Spain falls mainly in the plain!"
#Check if the string contains "a" followed by exactly two "l" characters
: x = re.findall("al{2}", txt)
print(x) if
x:
print("Yes, there is at least one match!") else:
print("No match")
OUTPUT:
['all']
Yes, there is at least one match!
20
Python Lab Manual
#| :
import re
txt = "The rain in Spain falls mainly in the plain!"
#Check if the string contains either "falls" or "stays"
: x = re.findall("falls|stays", txt)
print(x)
if x:
print("Yes, there is at least one match!")
else:
print("No match")
OUTPUT:
['falls']
Yes, there is at least one match!
#[arn] :
import re
txt = "The rain in Spain"
#Check if the string has any a, r, or n
characters: x = re.findall("[arn]", txt)
print(x
) if x:
print("Yes, there is at least one
match!") else:
print("No match")
OUTPUT:
#[a-n] :
import re
txt = "The rain in Spain"
#Check if the string has any characters between a and
n: x = re.findall("[a-n]", txt)
print(x
) if x:
print("Yes, there is at least one
match!") else:
print("No match")
OUTPUT:
['h', 'e', 'a', 'i', 'n', 'i', 'n', 'a', 'i', 'n']
Yes, there is at least one match!
#[0123] :
txt = "The rain in Spain"
21
Python Lab Manual
#Check if the string has any 0, 1, 2, or 3
digits: x = re.findall("[0123]", txt)
print(x
) if x:
print("Yes, there is at least one
match!") else:
print("No match")
OUTPUT:
[]
No match
#[0-9]:
import re
txt = "8 times before 11:45 AM"
#Check if the string has any
digits: x = re.findall("[0-9]",
txt)
print(x
) if x:
print("Yes, there is at least one
match!") else:
print( No match )
OUTPUT:
Exercise 4
22
Python Lab Manual
a) Implement Class and object
#Class
class Person:
def init (self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("Suchetha",
20)#Object print(p1.name)
print(p1.age
)
p1.myfunc()
OUTPUT:
Sucheth
a 20
Hello my name is Suchetha
b) Write a program to implement static and instance methods,abstract classes and interfaces
#Static Method :
class Mathematics:
def addNumbers(x,
y): return x + y
# create addNumbers static method
Mathematics.addNumbers =
staticmethod(Mathematics.addNumbers) print('The sum is:',
Mathematics.addNumbers(5, 10))
OUTPUT:
#Instance Method :
class shape:
# Calling Constructor
def init (self, edge, color):
self.edge = edge
self.color = color
# Instance Method
def
23
Python Lab Manual
finEdges(self):
return self.edge
# Instance Method
def modifyEdges(self,
newedge): self.edge =
newedge
circle = shape(0, 'red')
square = shape(4, 'blue')
# Calling Instance
Method
square.modifyEdges(6)
OUTPUT:
No. of edges for circle:
0 No. of edges for
square: 6
#Abstract Class:
from abc import ABC,
@abstractmethod
def
noofsides(self)
: pass
class Triangle(Polygon):
# overriding abstract
method def noofsides(self):
print("I have 3
sides") class
Pentagon(Polygon):
# overriding abstract
method def noofsides(self):
print("I have 5
sides") class
24
Python Lab Manual
Quadrilateral(Polygon):
# overriding abstract
method def noofsides(self):
print("I have 4 sides")
# Driver code
R =
Triangle()
R.noofsides()
K =
Quadrilateral()
K.noofsides()
R =
Pentagon()
R.noofsides()
OUTPUT:
I have 3 sides
I have 4
sides I have
5 sides
#Interfaces:
import zope.interface
class
MyInterface(zope.interface.Interface):
x = zope.interface.Attribute("foo")
def method1(self,
x): pass
def
method2(self)
: pass
print(type(MyInterface))
print(MyInterface. module )
print(MyInterface. name
) # get attribute
x =
MyInterface['x']
print(x)
print(type(x))
25
Python Lab Manual
5 x =
zope.interface.Attribute("foo")
c) Write a program to compute distance between two points taking input from the
user (Pythogorean Theorem)
x1=int(input("enter x1 :
")) x2=int(input("enter
x2 : "))
y1=int(input("enter y1 :
")) y2=int(input("enter y2
: "))
OUTPUT:
enter x1 : 45
enter x2 : 67
enter y1 : 89
enter y2 : 56
Distance between (45, 67) and (89, 56) is : 39.66106403010388
26
Python Lab Manual
Exercise 5
#Inheritance :
class
Person(object):
# Constructor
def init (self, name):
self.name = name
# To get name
def getName(self):
return self.name
# Here we return
true def
27
Python Lab Manual
isEmployee(self):
return True
# Driver code
emp = Person("Suchetha") # An Object of Person
print(emp.getName(), emp.isEmployee())
OUTPUT:
Suchetha
False Sunitha
True
#Polymorphism :
class DS():
def about(self):
print("DS is new branch in VJIT")
def sections(self):
print("There are 1 section of DS")
def members(self):
print("There are 61 students in DS")
class CSE():
def about(self):
print("CSE is old branch in VJIT")
def sections(self):
print("There are 4 sections of CSE in each year")
def members(self):
print("There are 240 students in CSE first year")
obj_ai= DS()
obj_cse = CSE()
for branch in (obj_ai,
obj_cse): branch.about()
branch.sections(
)
branch.members()
OUTPUT:
DS is new branch in VJIT
There are 1 section of DS
There are 61 students in
DS CSE is old branch in
VJIT
There are 4 sections of CSE in each
28
Python Lab Manual
year There are 240 students in CSE
first year
#Create a File :
file = open('new.txt','w')
file.write("This is the write command\n")
file.write("It allows us to write in a particular
file") file.close()
OUTPUT:
This is the write command
It allows us to write in a particular file
# Python code to illustrate read() mode character wise
file = open("new.txt",
"r") print (file.read(6))
OUTPUT:
This i
29
Python Lab Manual
OUTPUT:
This is the write command
#Write:
with open('app.log', 'w') as
f: #first line
f.write('my first file\
n') #second line
f.write('This file\
n') #third line
f.write('contains three lines\n')
30
Python Lab Manual
with open('app.log', 'r') as
f: content = f.readlines()
for line in
content:
print(line)
OUTPUT:
my first
file This
file
contains three lines
#Division by 0: ^
SyntaxError:
marks = 10000 invalid syntax
# performSEARCH STACK
division with OVERFLOW
0a=
marks / 0
print(a)
31
Python Lab Manual
3 if(amount>18)
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
except IndexError:
print ("An error occurred")
OUTPUT:
Second element =
2 An error
occurred
Exercise 6
#Required
libraries import
pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import
LabelEncoder from sklearn.preprocessing
import MinMaxScaler import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
train_url =
"http://s3.amazonaws.com/assets.datacamp.com/course/Kaggle/train.csv" train =
pd.read_csv(train_url)
test_url = "http://s3.amazonaws.com/assets.datacamp.com/course/Kaggle/test.csv"
32
Python Lab Manual
test = pd.read_csv(test_url)
print("***** Train_Set
*****") print(train.head())
print("\n")
print("***** Test_Set
*****") print(test.head())
[5 rows x 12 columns]
[5 rows x 11 columns]
print("Train
shape",train.shape) print("Test
shape",test.shape)
print("***** Train_Set
*****")
print(train.describe())
print("\n")
print("***** Test_Set
*****")
print(test.describe())
33
Python Lab Manual
50% 446.000000 0.000000 3.000000 ... 0.000000 0.000000 14.454200
75% 668.500000 1.000000 3.000000 ... 1.000000 0.000000 31.000000
max 891.000000 1.000000 3.000000 ... 8.000000 6.000000 512.329200
[8 rows x 7 columns]
34
Python Lab Manual
min 892.000000 1.000000 0.170000 0.000000 0.000000 0.000000
25% 996.250000 1.000000 21.000000 0.000000 0.000000 7.895800
50% 1100.500000 3.000000 27.000000 0.000000 0.000000 14.454200
75% 1204.750000 3.000000 39.000000 1.000000 0.000000 31.500000
max 1309.000000 3.000000 76.000000 8.000000 9.000000 512.329200
print(train.columns.values
)
print(test.columns.values)
PassengerId Survived Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embark
0 False False False False False False False False False False True Fa
1 False False False False False False False False False False False Fa
2 False False False False False False False False False False True Fa
3 False False False False False False False False False False False Fa
4 False False False False False False False False False False True Fa
PassengerId Pclass Name Sex Age SibSp Parch Ticket Fare Cabin Embarked
0 False False False False False False False False False True False
1 False False False False False False False False False True False
2 False False False False False False False False False True False
3 False False False False False False False False False True False
4 False False False False False False False False False True False
35
Python Lab Manual
set*****")
print(train.isna().sum())
print("\n")
print("*****In the test
set*****")
print(test.isna().sum())
PassengerId 0
Survived 0
Pclass 0
Name 0
Sex 0
Age 0
SibSp 0
36
Python Lab Manual
Parch 0
Ticket 0
Fare 0
Cabin 687
Embarked 2
dtype: int64
PassengerId 0
Pclass 0
Name 0
Sex 0
Age 0
SibSp 0
Parch 0
Ticket 0
Fare 0
Cabin 327
Embarked 0
dtype: int64
train['Ticket'].head()
0 A/5 21171
1 PC 17599
2 STON/O2. 3101282
3 113803
4 373450
Name: Ticket, dtype: object
train['Cabin'].head()
0 NaN
1 C85
2 NaN
3 C123
4 NaN
Name: Cabin, dtype: object
#Age vs survived
g = sns.FacetGrid(train,
col='Survived') g.map(plt.hist, 'Age',
bins=20)
<seaborn.axisgrid.FacetGrid at 0x7f0d20ec3c90>
37
Python Lab Manual
train.info()
left train.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to
890 Data columns (total 7
columns):
# Column Non-Null Count Dtype
<class
'pandas.core.frame.DataFrame'>
RangeIndex: 418 entries, 0 to 417
Data columns (total 6 columns):
# Column Non-Null Count Dtype
X = np.array(train.drop(['Survived'], 1).astype(float))
Y= np.array(train['Survived'])
kmeans = KMeans(n_clusters=2) # You want cluster the passenger records into 2: Survived or Not
survi kmeans.fit(X)
39
Python Lab Manual
correct = 0
for i in range(len(X)):
predict_me = np.array(X[i].astype(float))
predict_me = predict_me.reshape(-1,
len(predict_me)) prediction =
kmeans.predict(predict_me)
if prediction[0] ==
Y[i]: correct += 1
predict_me.shap
e (1, 6)
print(predict_me)
[[ 3. 1. 32. 0. 0. 7.75]]
print(correct/
len(X))#Score
0.6442199775533108
correct = 0
for i in range(len(X)):
predict_me = np.array(X[i].astype(float))
predict_me = predict_me.reshape(-1,
len(predict_me)) prediction =
kmeans.predict(predict_me)
if prediction[0] ==
Y[i]: correct += 1
print(correct/len(X))
40
Python Lab Manual
0.6442199775533108
scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)
kmeans.fit(X_scaled)
correct = 0
for i in range(len(X)):
predict_me = np.array(X[i].astype(float))
predict_me = predict_me.reshape(-1,
len(predict_me)) prediction =
kmeans.predict(predict_me)
if prediction[0] ==
Y[i]: correct += 1
print(correct/len(X))
0.2772166105499439
The entropy (very common in Information Theory) characterizes the (im)purity of an arbitrary collection
of examples
If we have a set with k different values in it, we can calculate the entropy as follows:
Where P(valuei) is the probability of getting the ith value when randomly selecting one from the set. So, for
41
Python Lab Manual
the set R = {a,a,a,b,b,b,b,b}
import numpy as
np import math
import pandas as pd
Data=np.array([["Jeff",32,0,1,1,1],["Pete",25,1,1,0,1],["Anne",33,1,1,0,1],["Natalie",26,0,0,1,0],["
["Sarah",29,1,0,1,0],["David",35,1,0,0,1],["Eric",28,1,1,1,0],["Mike",20,0,1,0,1],["Karen",38,
Data=pd.DataFrame(Data,columns=("Names","Age","Apple_pie","Potato_salad","Sushi","Mid_west"))
Data
42
Python Lab Manual
Names Age Apple_pie Potato_salad Sushi Mid_west
0 Jeff 32 0 1 1 1
1 Pete 25 1 1 0 1
2 Anne 33 1 1 0 1
3 Natalie 26 0 0 1 0
4 Stella 30 1 1 1 1
5 Rob 25 1 0 0 1
6 Joe 42 1 1 0 1
7 Jim 38 1 1 0 1
8 Lisa 36
def calc_entropy(column): 1 1 0 0
# Compute the counts of each unique value in the
9 Sarah 29 1 0 1 0
column counts = np.bincount(column)
# Divide
10 by the35total column
David 1 length to get0 a 0 1
probability probabilities = counts / len(column)
11 Eric 28 1 1 1 0
# Initialize the entropy to
12 Mike 20 0 1 0 1
0 entropy = 0
# Loop through 38
13 Karen the probabilities,
1 and add0 each one
0 to the 1total
entropy for prob in probabilities:
14ifMegan
prob > 0:31 0 0 1 0
# use log from math and set base to
2 entropy += prob * math.log(prob,
2)
return -entropy
If we want to split the data as follows with root node of potato salad
43
Python Lab Manual
44
Python Lab Manual
# Return information gain
return original_entropy - to_subtract
calc_entropy(Data["Mid_west"])#entropy before
split 0.9182958340544896
45
Python Lab Manual
#Information gain when splitted by potato_salad
column
calc_information_gain(Data,"Potato_salad","Mid_west")
0.0597731301493174
print("Information gains:
highest value
return max(information_gains, key=information_gains.get)
Best_split=highest_info_gain(columns)
print("The data has to be splitted by ",Best_split," in order to get more information gain")
46
Python Lab Manual
So we
need to
split the
data as
follows in c) Program to implement perceptron
order to
get more
informati
on gain
47
Python Lab Manual
from centers=2,cluster_std=1.05,
sklearn random_state=2)
import
datasets
X, Y =
datasets.mak
e_blobs(n_sa
mples=150,n_
features=2,
#Plotting
fig = plt.figure(figsize=(10,8))
plt.plot(X[:, 0][Y == 0], X[:, 1][Y== 0], 'r^')
plt.plot(X[:, 0][Y == 1], X[:, 1][Y == 1], 'bs')
plt.xlabel("feature 1")
plt.ylabel("feature 2")
plt.title('Random Classification Data with 2 classes')
print(X)
[[-5.32783010e-01 -
1.64847081e+00] [-5.50226372e-01
-1.16166152e+01]
[ 1.38862276e+00 -
48
Python Lab Manual
1.43580590e+00] [ 1.37033956e+00
-6.40220712e-01] [-8.80606388e-
01 -9.70946740e+00] [-
2.22746033e+00 -1.01019963e+01]
[-3.83660791e+00 -
9.36311253e+00] [-2.61500332e-01
-1.80587922e+00]
[ 1.18267985e+00 -7.12729660e-
01] [-8.91135194e-01 -
8.05385981e+00] [-3.42244116e+00
-9.43290706e+00] [-
3.24159714e+00 -7.66373146e+00]
[-8.14411765e-02 -
1.76413571e+00] [ 2.82215236e+00
-1.76342807e+00]
[ 1.90632766e+00 -
2.43499725e+00] [ 1.12041042e+00
-2.18272234e+00] [ 4.12652646e-
01 -9.79048994e-01] [-
1.61986103e+00 -9.03645942e+00]
[ 1.24676117e+00 -7.71255216e-
01] [-2.01362140e+00 -
1.04568119e+01]
49
Python Lab Manual
[-6.48510353e-01 -9.47763290e+00]
[ 1.90763236e+00 -6.71105011e-
01] [-7.57264801e-01 -
9.34864598e+00] [ 2.18263294e+00
-9.04732063e-01]
[ 1.53216357e+00 -
1.64513848e+00] [ 1.12431439e+00
-4.99224897e-01]
[ 1.19440189e+00 -
1.98887161e+00] [-2.43377785e+00
-7.81776395e+00] [ 3.50550070e-
01 -1.66237773e+00] [-
7.52076469e-01 -1.07890279e+01]
[ 8.37695007e-01 2.82956613e-
01] [ 1.86418091e+00 -
6.31399082e-01] [ 2.07793008e+00
-1.63900470e+00] [-
3.16320932e+00 -1.03653101e+01]
[ 2.09100144e+00 1.43914678e-01]
[-1.51976189e+00 -
1.16545682e+01] [ 1.57354644e+00
-2.17601731e+00] [-
1.23648559e+00 -1.06552971e+01]
[-2.89251066e-01 6.01148326e-
01] [ 2.60959954e-01 -
9.83393657e+00] [ 1.39785819e+00
-1.10283073e+01] [-8.24930811e-
01 -8.13917717e+00] [-
1.63748148e+00 6.23742032e-01]
[-1.76520757e+00 -
9.11304244e+00] [ 5.01485985e-01
-2.61100847e+00] [ 6.65365354e-
01 9.58359846e-01] [-
1.05318015e+00 -1.14330184e+01]
[ 6.02120538e-01 -
9.93193935e+00] [-8.79142411e-01
-8.88688615e+00] [ 3.69806196e-
01 -8.65765515e-02] [-
1.94963972e+00 -1.07284683e+01]
[ 1.05673513e+00 -
2.69907047e+00] [ 2.16363071e+00
-8.46207098e+00] [-4.14163801e-
01 -8.17085180e+00] [-
4.78938837e-02 -1.19422587e+01]
[-1.47904469e+00 -
9.56255496e+00] [-1.01070298e+00
-1.05196934e+01] [-
1.94651523e+00 -8.94765931e+00]
[-2.76985304e+00 -
9.74583819e+00]
print(Y)
[1 0 1 1 0 0 0 1 1 0 0 0 1 1 1 1 1 0 1 0 0 1 0 1 1 1 1 0 1 0 1 1 1 0 1 0 1
0 1 0 0 0 1 0 1 1 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 1 1 0 1 0 1 0 1 1 0 1 1 1
1 0 1 0 1 1 1 1 1 1 0 1 1 1 1 0 0 1 1 1 0 0 0 1 1 0 0 0 1 1 0 1 0 0 0 1 0
50
Python Lab Manual
1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 1 0 0 1 1 1 0 1 1 1 0 1 0 1 0 0 0 0 1 0
1 1]
Step function
def step_func(z):
return 1.0 if (z > 0) else 0.0
#Backward propogation
def perceptron(X, y, lr, epochs):
# X --> Inputs.
# y --> labels/target.
# lr --> learning
rate.
# epochs --> Number of iterations.
# Initializing parapeters(theta) to
zeros. # +1 in n+1 for the bias term.
theta = np.zeros((n+1,1))
# Training.
for epoch in range(epochs):
51
Python Lab Manual
# variable to store
#misclassified. n_miss = 0
# Calculating prediction/hypothesis.
y_hat = step_func(np.dot(x_i.T, theta))
# Incrementing by
1. n_miss += 1
m, n = X.shape
theta = np.zeros((n+1,1))
theta
array([[0.],[0.],[0.]])
theta
miss_l
[14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
#Forward
propogation/prediction
x_test=[[2.7525,-3.7423]]
52
Python Lab Manual
x_test = np.insert(x_test, 0, 1).reshape(-
1,1) x_test
array([[ 1. ],[2.7525],[-3.7423]])
1.0
Exercise 7
a)Generate a decision tree.Find the depth of decision trees and observe the
results,then propose some changes in DecisionTreeClassifier function to limit.
import numpy as np
import pandas as pd
from sklearn.datasets import
load_iris from sklearn import tree
from sklearn.model_selection import train_test_split
iris = load_iris()
X, Y= iris.data, iris.target
X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.4,random_state=6)
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X_train, Y_train)
53
Python Lab Manual
[4.9, 3.1, 1.5, 0.1],
[5.4, 3.7, 1.5, 0.2],
[4.8, 3.4, 1.6, 0.2],
[4.8, 3. , 1.4, 0.1],
[4.3, 3. , 1.1, 0.1],
[5.8, 4. , 1.2, 0.2],
[5.7, 4.4, 1.5, 0.4],
[5.4, 3.9, 1.3, 0.4],
[5.1, 3.5, 1.4, 0.3],
[5.7, 3.8, 1.7, 0.3],
[5.1, 3.8, 1.5, 0.3],
[5.4, 3.4, 1.7, 0.2],
[5.1, 3.7, 1.5, 0.4],
[4.6, 3.6, 1. , 0.2],
[5.1, 3.3, 1.7, 0.5],
[4.8, 3.4, 1.9, 0.2],
[5. , 3. , 1.6, 0.2],
[5. , 3.4, 1.6, 0.4],
[5.2, 3.5, 1.5, 0.2],
[5.2, 3.4, 1.4, 0.2],
[4.7, 3.2, 1.6, 0.2],
[4.8, 3.1, 1.6, 0.2],
[5.4, 3.4, 1.5, 0.4],
[5.2, 4.1, 1.5, 0.1],
[5.5, 4.2, 1.4, 0.2],
[4.9, 3.1, 1.5, 0.2],
[5. , 3.2, 1.2, 0.2],
[5.5, 3.5, 1.3, 0.2],
[4.9, 3.6, 1.4, 0.1],
[4.4, 3. , 1.3, 0.2],
[5.1, 3.4, 1.5, 0.2],
[5. , 3.5, 1.3, 0.3],
[4.5, 2.3, 1.3, 0.3],
[4.4, 3.2, 1.3, 0.2],
[5. , 3.5, 1.6, 0.6],
[5.1, 3.8, 1.9, 0.4],
[4.8, 3. , 1.4, 0.3],
[5.1, 3.8, 1.6, 0.2],
[4.6, 3.2, 1.4, 0.2],
[5.3, 3.7, 1.5, 0.2],
[5. , 3.3, 1.4, 0.2],
[7. , 3.2, 4.7, 1.4],
[6.4, 3.2, 4.5, 1.5],
[6.9, 3.1, 4.9, 1.5],
[5.5, 2.3, 4. , 1.3],
[6.5, 2.8, 4.6, 1.5],
[5.7, 2.8, 4.5, 1.3],
[6.3, 3.3, 4.7, 1.6],
[4.9, 2.4, 3.3, 1. ],
[6.6, 2.9, 4.6, 1.3],
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
54
Python Lab Manual
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
iris.target_names
iris.feature_names
['sepal length
(cm)', 'sepal width
(cm)', 'petal
length (cm)',
'petal width (cm)']
tree.plot_tree(clf)
print(clf)
print("Max depth:",clf.max_depth)#max depth
55
Python Lab Manual
DecisionTreeClassifier(ccp_alpha=0.0, class_weight=None, criterion='gini',
max_depth=None, max_features=None,
max_leaf_nodes=None, min_impurity_decrease=0.0,
min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0,
presort='deprecated', random_state=None,
splitter='best')
Max depth: None
Ypred=clf.predict(X_test)
Ypred
array([0, 2, 0, 0, 2, 1, 1, 0, 2, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 0, 0, 2,
0, 0, 1, 1, 1, 2, 0, 1, 0, 1, 0, 0, 1, 2, 1, 2, 1, 0, 0, 2, 1, 1,
0, 0, 1, 0, 0, 1, 2, 2, 2, 0, 2, 0, 0, 0, 1, 2])
print(Score)
0.95
clf =
tree.DecisionTreeClassifier(max_depth=8,random_state=5) clf
= clf.fit(X_train, Y_train)
print(clf)
print("Max depth:",clf.max_depth)#max depth
Ypred=clf.predict(X_test)
Ypred
array([0, 2, 0, 0, 2, 1, 2, 0, 2, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 0, 0, 2,
0, 0, 1, 1, 1, 2, 0, 1, 0, 1, 0, 0, 1, 2, 1, 2, 1, 0, 0, 2, 1, 1,
0, 0, 1, 0, 0, 1, 2, 2, 2, 0, 2, 0, 0, 0, 1, 2])
56
Python Lab Manual
Score=accuracy_score(Y_test,Ypred)
print(Score)#Score is changed from 0.95 to
0.96 0.9666666666666667
Exercise 8
import numpy as np
#inv
x = np.array([[1,2],
[3,4]]) y =
np.linalg.inv(x)
print(x
)
print(y
)
[[1 2]
[3 4]]
[[-2. 1. ]
[ 1.5 -0.5]]
#pinv
x = np.array([[1,2],
[3,4]]) y =
np.linalg.pinv(x)
print(x
)
print(y
)
[[1 2]
[3 4]]
[[-2. 1. ]
[ 1.5 -0.5]]
#matrix_rank
57
Python Lab Manual
x = np.array([[1,2],[3,4]])
y =
np.linalg.matrix_rank(x)
print(x)
print(y)
[[1 2]
[3 4]]
2
#solve
x = np.array([[1,2],[3,4]])
#1*x0+2*x1=8,3*x0+4*x1 b=np.array([8,16])
y = np.linalg.solve(x,b) #x0 are x1 are solved
print(x)
print(y)
[[1 2]
[3 4]]
[0. 4.]
#By examining the coefficients, we see that the line should have a gradient of roughly 1 and cut
the
#We can rewrite the line equation as y = Ap, where A = [[x 1]] and p = [[m], [c]]. Now use lstsq to
A = np.vstack([x,
np.ones(len(x))]).T print("A is:\
n",A)
m, c = np.linalg.lstsq(A, y, rcond=None)
[0] print("m and c are:",m,c)
#svd-Singular value
smat=np.zeros((3,2))
smat[:2,:2]=np.diag(S) print("\
nSmat:")
print(smat)
A_D=np.linalg.multi_dot([U,smat,VT]
) print("\nBefore decomposition")
print(A)
print("\nAfter
decomposition") print(A_D)
Singular values
[3.31662479 1. ]
[[-0.70710678 -0.70710678]
[-0.70710678 0.70710678]]
Smat:
[[3.31662479 0. ]
[0. 1. ]
[0. 0. ]]
Before decomposition
[[1 2]
[2 1]
[1 1]]
After decomposition
[[1. 2.]
[2. 1.]
[1. 1.]]
#transpose
A=np.array([[1,2],[2,1],[3,9]])
print("Orginal matrix
A") print(A)
print("\nTranspose of matrix
A:") print(np.transpose(A))
Orginal matrix A
[[1 2]
[2 1]
[3 9]]
Transpose of matrix
A: [[1 2 3]
[2 1 9]]
#eig-Ax=Lamba*x
A=np.array([[4,1],[6,3]])
print("Orginal array
A") print(A)
e_val,e_vec=np.linalg.eig(A)
print("\nEigen
value:") print(e_val)
print("\nEigen
60
Python Lab Manual
vector:") print(e_vec)
print("\nAx=")
print(np.dot(A,e_vec))
print("\
nLamba*x")
print(e_val*e_vec
)
Orginal array
A [[4 1][6 3]]
Eigen
value: [6.
1.]
61
Python Lab Manual
Eigen vector:
[[ 0.4472136 -0.31622777]
[ 0.89442719 0.9486833 ]]
Ax=
[[ 2.68328157 -0.31622777]
[ 5.36656315 0.9486833 ]]
Lamba*x
[[ 2.68328157 -0.31622777]
[ 5.36656315 0.9486833 ]]
#sort
a = np.array([[1,4],
[3,1]]) print("Orginal
array:")
print(a)
Orginal array:
[[1 4]
[3 1]]
#linspace
print("\n5 Numbers between 2.0 and 3.0 with end point and
step") print(np.linspace(2.0, 3.0, num=5, retstep=True))
#meshgrid
xa, xb = np.meshgrid(a,
b,sparse=True) print(xa)
print(xb)
#mgrid
print(np.mgrid[0:5,0:5])
print(np.mgrid[-1:1:5j])
[[[0 0 0 0 0]
[1 1 1 1 1]
[2 2 2 2 2]
[3 3 3 3 3]
[4 4 4 4 4]
]
[[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
]]
[-1. -0.5 0. 0.5 1. ]
#ogrid
print(np.ogrid[-1:1:5j])
print(np.ogrid[0:5,0:5])
#concatenate
print(np.concatenate((a, b.T),
axis=1))
[[1 2]
[3 4]
[5 6]]
[[1 2 5]
[3 4 6]]
[1 2 3 4 5 6]
#tile
a = np.array([0, 1, 2])
print(np.tile(a, 2))
print("\n",np.tile(b, (2,
1))) c = np.array([1,2,3,4])
print("\n","\n",np.tile(c,(4,1)))
[0 1 2 0 1 2]
[[0 1 2 0 1 2]
[0 1 2 0 1 2]]
[[[0 1 2 0 1 2]]
[[0 1 2 0 1 2]]]
[[1 2 1 2]
[3 4 3 4]]
[[1 2]
[3 4]
[1 2]
[3 4]]
[[1 2 3 4]
[1 2 3 4]
[1 2 3 4]
[1 2 3 4]]
65
Python Lab Manual
#squeeze
x = np.array([[[0], [1], [2]]])
print(x.shape)
print(np.squeeze(x).shape)
print(np.squeeze(x, axis=0).shape)
print(np.squeeze(x,
axis=2).shape) x =
np.array([[1234]])
print(x.shape)
print(np.squeeze(x))
print(np.squeeze(x).shape
) print(np.squeeze(x)
[()])
(1, 3, 1)
(3,)
(3, 1)
(1, 3)
(1, 1)
123
4
()
1234
66
Python Lab Manual
Exercise 9
#download a dataset
data=load_iris()
data.feature_names
['sepal length
(cm)', 'sepal width
(cm)', 'petal
length (cm)',
'petal width (cm)']
X=data.dat
a X
68
Python Lab Manual
[4.6, 3.2, 1.4, 0.2],
[5.3, 3.7, 1.5, 0.2],
[5. , 3.3, 1.4, 0.2],
[7. , 3.2, 4.7, 1.4],
[6.4, 3.2, 4.5, 1.5],
[6.9, 3.1, 4.9, 1.5],
[5.5, 2.3, 4. , 1.3],
[6.5, 2.8, 4.6, 1.5],
[5.7, 2.8, 4.5, 1.3],
[6.3, 3.3, 4.7, 1.6],
[4.9, 2.4, 3.3, 1. ],
[6.6, 2.9, 4.6, 1.3],
Y=data.targe
t Y
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
print(type(data)
) print(X.shape)
print(Y.shape)
<class
'sklearn.utils.Bunch'> (150,
4)
(150,)
datapd=pd.DataFrame(x,columns=data.feature_names)
datapd
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
69
Python Lab Manual
146 6.3 2.5 5.0 1.9
datapd.isnull().sum()
sepal length (cm) 0
sepal width (cm) 0
petal length (cm) 0
petal width (cm) 0
dtype: int64
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
10 110
11 111
12 112
13 113
14 114
15 115
16 116
17 117
18 118
19 119
20 120
21 121
22 122
23 123
24 124
25 125
26 126
dtype: int64
#Plot
x= [1,2,3,4]
y=[2,4,6,8]
plt.plot(x,y,'g', linewidth=3.0)
plt.ylabel('number*2'
)
plt.xlabel("number")
plt.title('Plot')
plt.show()
#Bar
Number_of_people = [1,3,5,7,9]
age= [5,2,7,8,2]
plt.xlabel("age")
plt.ylabel("no.of
people") plt.title("Bar
graph")
71
Python Lab Manual
plt.show()
# histogram
students_marks= [11,12,13,56,67,45,22,21]
marks = [0,10,20,30,40,50,60,70,80,90,100]
plt.xlabel('marks')
plt.ylabel('no. of
students')
plt.title('Histogram')
plt show()
x1=[8,8.5,9,9.5,10,10.5,11]
72
Python Lab Manual
y1=[3,3.5,3.7,4,4.5,5,5.2]
#pie
Cities=["Hyderabad","Delhi","Agra"
# Creating plot
fig = plt.figure(figsize =(10, 7))
plt.pie(people_like, labels
=Cities ) plt.title("Pie chart")
# show plot
plt.show()
73
Python Lab Manual
Exercise 10
#Simple plot
# x axis
values x =
[1,2,3,8,6]
# corresponding y axis
values y = [2,4,1,7,8]
# plotting the
points plt.plot(x,
y)
# giving a title to my
graph plt.title('My first
graph!')
74
Python Lab Manual
# line 1 points
x1 =
[2,4,6,7,8]
y1 = [2,4,1,9,0]
# plotting the line 1 points
plt.plot(x1, y1, label = "line 1",color="b")
# line 2 points
x2 =
[1,2,3,6,1,]
y2 = [4,1,3,10,5]
# plotting the line 2 points
plt.plot(x2, y2, label = "line 2",color='r')
#customise
# x axis values
75
Python Lab Manual
x =
[1,2,3,4,5,6]
# corresponding y axis
values y = [2,4,1,5,2,6]
# giving a title to my
graph
plt.title('Customizations!'
)
#subplot
# x axis values
x1 =
[1,2,3,8,6]
# corresponding y axis
values y1 = [2,4,1,7,8]
76
Python Lab Manual
x2=[4,6,2,3,9]
y2=[6,7,1,1,2]
x3=[2,4,5,7,1,3]
y3=[6,2,3,1,1,9]
# plotting the
points
plt.subplot(2,3,1)
plt.plot(x1, y1,'b*--')
plt.subplot(2,3,2)
plt.plot(x2, y2,'g--')
plt.subplot(2,3,3)
plt.plot(x3, y3,'ro--')
plt.subplot(2,3,4)
plt.plot(x3, y3,'bo--')
77
Python Lab Manual
[<matplotlib.lines.Line2D at 0x7f0d211c4650>]
#pie
# defining labels
firstyear = ['AI', 'CSE', 'EEE', 'IT']
# showing the
plot plt.show()
78
Python Lab Manual
Exercise 11
#2D
u=[4,-1]
v=[-1,9]
fig=plt.figur
e
ax=plt.axes()
ax.set_xlim([-5,5])
ax.set_ylim([-10,10])
start=[0,0]
ax.quiver(start[0],start[1],u[0],u[1],color='blue')
ax.quiver(start[0],start[1],v[0],v[1],color='green')
<matplotlib.quiver.Quiver at 0x7f9f98f5e6d0>
#3D
u=[4,5,-7]
v=[-1,4,9]
w=[1,-3,5]
fig=plt.figure
ax=plt.axes(projection='3d'
) ax.set_xlim([-1,10])
ax.set_ylim([-5,8])
ax.set_zlim([-10,10])
79
Python Lab Manual
start=[0,0,0]
ax.quiver(start[0],start[1],start[2],u[0],u[1],u[2],color='blue')
ax.quiver(start[0],start[1],start[2],v[0],v[1],v[2],color='green')
ax.quiver(start[0],start[1],start[2],w[0],w[1],w[2],color='red')
<mpl_toolkits.mplot3d.art3d.Line3DCollection at 0x7f9fa76a7a90>
80