5 Python Notes Aug 30 To 08 Sept 2022
5 Python Notes Aug 30 To 08 Sept 2022
=>To implement Data Encapsulation in python programming, The Data Members , Methods must be
preceded with double under score ( _ _ )
(OR)
class <ClassName>:
def __init__(self):
self.__Data MemberName1=Value1
self.__Data MemberName2=Value2
------------------------------------------------
self.__Data MemberName-n=Value-n
class <ClassName>:
def __methodname(self):
self.Data MemberName1=Value1
self.Data MemberName2=Value2
------------------------------------------------
self.Data MemberName-n=Value-n
Example1:
---------------------
#account.py----file name and treated as module name
class Account:
def getaccountdet(self):
self.__acno=34567
self.cname="Rossum"
self.__bal=34.56
self.bname="SBI"
self.__pin=1234
self.pincode=4444444
#here acno,bal and pin are encapsulated
Example2:
---------------------
#account1.py----file name and treated as module name
class Account1:
def __getaccountdet(self): # here __getaccountdet() is made is encapsulated
self.acno=34567
self.cname="Rossum"
self.bal=34.56
self.bname="SBI"
self.pin=1234
self.pincode=4444444
Data Abstraction:
-------------------------------
=>The Process of retrieving / extracting Essential Details without considering Hidden Details is called
Data Abstraction.
--------------------------------------------------------------------------------------------------------------
Note:- We can't apply Data Encapsulation on Constructors in Python but whose Initlized Data
Members can be encapsulated.
Example:
---------------------
#Account1.py--File Name and Acts as Module Name--Data Encapsulation--Data member level
class Account1:
def __init__(self):
self.__acno=1234
self.cname="Rossum"
self.__bal=45.78
self.__pin=4321
self.bname="SBI"
-------------------------------------------------------------------------------------------------------------------
Example:
---------------------
#Account2.py--File Name and Acts as Module Name--Data Encapsulation--Method Level
class Account2:
def __getaccdetails(self):
self.acno=1234
self.cname="Rossum"
self.bal=45.78
self.pin=4321
self.bname="SBI"
-------------------------------------------------------------------------------------------------------------------
Example:
---------------------
#Account3.py--File Name and Acts as Module Name--Data Encapsulation
#At constructor Level, we can't apply data encapsulation
class Account3:
def ______init__(self):
print("here this is not a constructor and acts as method:")
self.acno=1234
self.cname="Rossum"
self.bal=45.78
self.pin=4321
self.bname="SBI"
----------------------------------------------------------------------------------------------------------------------
Example:
---------------------
#Others1.py----Data Abstraction
from Account1 import Account1
ac=Account1() # Object Creation
#print("\nAccount Number:{}".format(ac.acno)) Can't access
print("Account Holder Name:{}".format(ac.cname))
#print("Account Balanace:{}".format(ac.bal)) Can't access
# print("Account PIN:{}".format(ac.pin)) Can't access
print("Account Banch Name:{}".format(ac.bname))
--------------------------------------------------------------------------------------------------------------------
Example:
---------------------
#Others2.py----Data Abstraction
from Account2 import Account2
ac=Account2() # Object Creation
ac.getaccdetails()
print("\nAccount Number:{}".format(ac.acno))
print("Account Holder Name:{}".format(ac.cname))
print("Account Balanace:{}".format(ac.bal))
print("Account PIN:{}".format(ac.pin))
print("Account Banch Name:{}".format(ac.bname))
---------------------------------------------------------------------------------------------------------------------------
Example:
---------------------
#Others3.py----Data Abstraction
from Account3 import Account3
ac=Account3() # Object Creation
ac.______init__()
print("\nAccount Number:{}".format(ac.acno))
print("Account Holder Name:{}".format(ac.cname))
print("Account Balanace:{}".format(ac.bal))
print("Account PIN:{}".format(ac.pin))
print("Account Banch Name:{}".format(ac.bname))
--------------------------------------------------------------------------------------------------------------------------
Example:
---------------------
#SameProgrammerEx1.py
class Account:
def __init__(self):
self.__acno=1234
self.cname="Rossum"
self.__bal=45.78
self.__pin=4321
self.bname="SBI"
def getaccess(self):
#print("\nAccount Number:{}".format(self.acno)) #Not Possible to access
print("Account Holder Name:{}".format(self.cname))
#print("Account Balanace:{}".format(self.bal)) #Not Possible to access
#print("Account PIN:{}".format(self.pin)) #Not Possible to access
print("Account Banch Name:{}".format(self.bname))
#main program
ac=Account()
ac.getaccess()
---------------------------------------------------------------------------------------------------------------------------
Example:
---------------------
#SameProgrammerEx2.py
class Account:
def __init__(self):
self.__acno=1234
self.cname="Rossum"
self.__bal=45.78
self.__pin=4321
self.bname="SBI"
def getaccess(self):
print("\nAccount Number:{}".format(self.__acno)) #Possible to Access
print("Account Holder Name:{}".format(self.cname))
print("Account Balanace:{}".format(self.__bal)) #Possible to Access
print("Account PIN:{}".format(self.__pin)) #Possible to Access
print("Account Banch Name:{}".format(self.bname))
#main program
ac=Account()
ac.getaccess()
------------------------------------------------------------------------------------------------------------------
Example:
---------------------
#SameProgrammerEx3.py
class Account:
def __init__(self):
self.__acno=1234
self.cname="Rossum"
self.__bal=45.78
self.__pin=4321
self.bname="SBI"
def __getaccess(self):
print("\nAccount Number:{}".format(self.__acno)) #Possible to Access
print("Account Holder Name:{}".format(self.cname))
print("Account Balanace:{}".format(self.__bal)) #Possible to Access
print("Account PIN:{}".format(self.__pin)) #Possible to Access
print("Account Banch Name:{}".format(self.bname))
def getAccount(self):
self.getaccess() # Calling Enacpsulated Instance Method from Other Instance
Method of same class--Not Possible
#main program
ac=Account()
ac.getAccount()
---------------------------------------------------------------------------------------------------------------------
Example:
---------------------
#SameProgrammerEx4.py
class Account:
def __init__(self):
self.__acno=1234
self.cname="Rossum"
self.__bal=45.78
self.__pin=4321
self.bname="SBI"
def __getaccess(self):
print("\nAccount Number:{}".format(self.__acno)) #Possible to Access
print("Account Holder Name:{}".format(self.cname))
print("Account Balanace:{}".format(self.__bal)) #Possible to Access
print("Account PIN:{}".format(self.__pin)) #Possible to Access
print("Account Banch Name:{}".format(self.bname))
def getAccount(self):
self.__getaccess() # Calling Enacpsulated Instance Method from Other Instance
Method of same class--Possible
#main program
ac=Account()
ac.getAccount()
----------------------------------------------------------------------------------------------------------------
Example:
---------------------
#TestSample.py
class Test:
def getTest(self):
print("getTest() of Test class")
class Sample:
def getSample(self):
print("getSample() of Sample Class")
# From here i want to call getTest() of Test Class
t=Test() # Has-a Relationship --creating an object of Test Class
t.getTest() # Calling Instance of Test class from instance Method of Sample class
#main program
s=Sample()
s.getSample()
=================================
Inheritance.
=================================
=>Purpose ofg Inheritance
=>Definition of Inheritance
=>Adavntages of Inheritance
=>Memory Management in Inheritance
=>Types of Inheritances
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
=>Syntax for Inheritance
=>Programming Examples
---------------------------------------------------------------
=================================
Inheritance.
=================================
=>The main purpose of Inheritance is that " To Build Re-Usable Applications in OOPs".
------------------------------------------
=>Definition of Inheritance:
------------------------------------------
=>The process of obtaining Data Members, Methods and Constructors from One Class into
Another Class is called Inheritance.
=>The Class Which is giving The Data Members , Methods and Constructors (Features of
Class) is called Base or Super or Parent Class
=>The Class Which is Taking The Data Members , Methods and Constructors (Features of
Class) is called Derived or Sub or Child Class.
--------------------------------------------------------------------------------------------------------------
=>The Inheritance principle always follows Logical Memory Management or Virtual Memory
Management. This Memory management says that "Neither we write source code nor takes physical
memory space ".
=>In Otherwords, Logical Memory Management or Virtual Memory Management makes us to
understand, all the features of Base Class can be inherited or avialble in derived class witout taking
Physical Memory space and Not writing physical Source Code."
--------------------------------------------------------------------------------------------------------------------------
Advantages of Inheritance
---------------------------------------------------------------------------------------------------------------------------
=>When we develop any inheritance based application, we get the following Advantages.
1. Single Inheritance
2. Multi Level Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance.
-----------------------------------------------------------------------
=====================================================
Inheriting the features of base class into derived class
=====================================================
=>To inherit the features of Base class into Derived class , we use the following Syntax.
class <classname-1>:
---------------------
---------------------
class <classname-2>:
---------------------
---------------------
class <classname-n>:
---------------------
---------------------
class <classname-n+1>(ClassName-1,ClassName-2....ClassName-n>):
---------------------
---------------------
--------------------
Explanation:
--------------------
=>Here ,ClassName-1,ClassName-2 ...ClassName-n are called Base Classes
=>Here classname-n+1 is called Derived Class
=>This Syntax Makes us to understand , All the features of Base Class(es) are availabe in
Derived class Logically or Virtually.
=>When we develop any Inheritance Based Application it is always recommended to cerate an
object of Bottom Most Derived Class bcoz It inherites the features of Intermediate Base Classes
and Top Most Base Class.
=>For Every Class in Python, Implicitly there exist a pre-defined super class called "object"
and it provides Garbage Collection Facility to its sub classes for collecting Un-used Memory space.
----------------------------------------------------------X-----------------------------------------------------
Example:
---------------------
#InhProg1.py
class BC:
city="HYD"
def getA(self):
self.a=10
class DC(BC):
def getB(self):
self.b=20
def operation(self):
self.getA() # calling Base Class Instance Method
self.getB()
c=self.a*self.b
print("Mul=",c)
print("city=",DC.city)
#Main program
do=DC()
do.operation()
#InhProg2.py
class C1:
def getA(self):
self.a=10
return self.a
class C2(C1):
def getB(self):
self.a=20
return self.a
class C3(C2):
def operation(self):
self.a=self.getA()+self.getB()
print("sum=",self.a)
#main program
o3=C3()
o3.operation()
---------------------------------------------------------------------------------------------------------------
Example:
---------------------
#InhProg3.py
class Univ:
def getunivdet(self):
self.uname=input("Enter University Name:")
self.uloc=input("Enter University Location:")
def dispunivdet(self):
print("-"*50)
print("University Details")
print("-"*50)
print("University Name:{}".format(self.uname))
print("University Location:{}".format(self.uloc))
print("-"*50)
class College(Univ):
def getcolldet(self):
self.cname=input("Enter College Name:")
self.cloc=input("Enter College Location:")
def dispcolldet(self):
print("-"*50)
print("College Details")
print("-"*50)
print("College Name:{}".format(self.cname))
print("College Location:{}".format(self.cloc))
print("-"*50)
class Student(College):
def getstuddet(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.crs=input("Enter Student Course:")
def dispstuddet(self):
print("-"*50)
print("Student Details")
print("-"*50)
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Stuednt Course:{}".format(self.crs))
print("-"*50)
#main program
s1=Student()
s1.getstuddet()
s1.getcolldet()
s1.getunivdet()
s1.dispunivdet()
s1.dispcolldet()
s1.dispstuddet()
---------------------------------------------------------------------------------------------------------------
Example:
---------------------
#Univ.py---file and acts as module name
class Univ:
def getunivdet(self):
self.uname=input("Enter University Name:")
self.uloc=input("Enter University Location:")
def dispunivdet(self):
print("-"*50)
print("University Details")
print("-"*50)
print("University Name:{}".format(self.uname))
print("University Location:{}".format(self.uloc))
print("-"*50)
----------------------------------------------------------------------------------------------------------------
Example:
---------------------
#College.py---file name and acts as module name
from Univ import Univ
class College(Univ):
def getcolldet(self):
self.cname=input("Enter College Name:")
self.cloc=input("Enter College Location:")
def dispcolldet(self):
print("-"*50)
print("College Details")
print("-"*50)
print("College Name:{}".format(self.cname))
print("College Location:{}".format(self.cloc))
print("-"*50)
---------------------------------------------------------------------------------------------------------
Example:
---------------------
#Student.py--file name and module name
from College import College
class Student(College):
def getstuddet(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.crs=input("Enter Student Course:")
self.getcolldet()
self.getunivdet()
def dispstuddet(self):
self.dispunivdet()
self.dispcolldet()
print("-"*50)
print("Student Details")
print("-"*50)
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Stuednt Course:{}".format(self.crs))
print("-"*50)
------------------------------------------------------------------------------------------------------------------------
Example:
---------------------
#UnivCollStud.py
from Student import Student
s=Student()
s.getstuddet()
s.dispstuddet()
==============================================
Polymorphism in Python
==============================================
=>Polymorphism is one of the distinct features of OOPs
=>The purpose of Polymorphism is that "Efficient Utilization Memory Spacee (OR) Less Memory
space is achieved".
----------------------------------------
=>Def. of Polymorphism:
----------------------------------------
=>The Process of Representing "One Form in multiple Forms " is called Polymorphism.
=>The Polymorphism Principle is implemented(Bring into action) by Using "Method Overriding"
feature of all OO Programming Languages.
=>In The definition of polymorphism, "One Form" represents "Original Method" and multiple forms
represents Overridden Methods.
=>A "Form" is nothing but existence of a Method. if the method is existing in base class then it is
called "Original Method(one form)" and if the method existing derived class(es) then it is called
"Overridden Method(multiple Forms)".
===========================================
Method Overriding in Python
===========================================
=>Method Overriding=Method Heading is same + Method Body is Different
(OR)
=>The process of re-defining the original method of base class into various derived classes for
performing different operations is called Method Overriding.
=>To use Method Overriding in python program we must apply Inheritance Principle.
=>Method Overriding used for implementing Polymorphism Principle.
Examples:
-----------------------
#methodoverex1.py
class Circle:
def draw(self): # original Method
print("Drawing Circle")
class Rect(Circle):
def draw(self): # overridden Method
print("Drawing Rect:")
super().draw()
class Square(Rect):
def draw(self): # overridden Method
print("Drawing Square:")
super().draw()
#main program
so=Square()
so.draw()
--------------------------------------------------------------------------------------------------------------
Example:
---------------------
#teacher.py
class Teacher:
def readsub(self):
print("Teacher advises to read 2 hours")
class LazyStudent(Teacher):
def readsub(self):
print("LazyStudent never read at all")
class PerfectStudent(Teacher):
def readsub(self):
print(" Perfect Student 2hrs reading and practicing")
ls=LazyStudent()
ls.readsub()
ps=PerfectStudent()
ps.readsub()
------------------------------------------------------------------------------------------------------
Example:
---------------------
#PolyMethodOverEx1.py
class Circle:
def draw(self): # Original Method
print("Drawing--Circle")
#super().draw() invalid, object does not contain draw()
class Rect(Circle):
def draw(self): # Method Overriding--Re-defined
print("Drawing-Rect")
class Square(Rect):
def draw(self): # Method Overriding
print("Drawing Square")
Circle.draw(self)
super().draw()
#main program
print("w.r.t Square Class")
s=Square()
s.draw()
=================================================
Number of approaches to call original methods / constructors from
Overridden methods / Constructors
=================================================
=>We have two approches to call original method / constructors of base class from overridden
method / constructors of derived class. They are
1) By using super()
2) By using Class Name
------------------------------------------------------------------------
1) By using super():
------------------------------------
=>super() is one of the pre-defined function, which is used for calling super class original method /
constructor from overridden method / constructors of derived class.
=>with super() we are able to call only immediate base class method but unable to call Specified
method of base Class . To do this we must use class name approach.
----------------------------------------------------------------
2) By using Class Name:
----------------------------------------------------------------
=>By using ClassName approach, we can call any base class method / constructor name from the
context of derived class method / constructor names.
class IBC(BC):
def __init__(self): # Overriddent Constructor
print("IBC--default Constructor")
class DC(IBC):
def __init__(self): # Overriddent Constructor
print("DC--default Constructor")
BC.__init__(self)
#main program
do=DC() # Object Creation
----------------------------------------------------------------------------------------------------------
Example:
---------------------
#PolyConstOverideEx2.py
class BC1:
def __init__(self): # Original Constructor
print("BC1--Default Constructor")
class BC2:
def __init__(self): # Original Constructor
print("BC2--default Constructor")
class DC(BC1,BC2):
def __init__(self): # Overridden Const
print("DC--default Constructor")
super().__init__() # Will call BC1 relataed Constructor
BC2.__init__(self)
#main program
do=DC() # Object Creation
------------------------------------------------------------------------------------------------------------
Example:
---------------------
#PolyMethodOverideEx3.py
class BC1:
def fun1(self,a): # Original Method
print("BC1--Fun1()--a={}".format(a))
class BC2:
def fun2(self,b): # Original Method
print("BC2--Fun2()--b={}".format(b))
class DC(BC1,BC2):
def fun3(self,a,b,c): # separate method
print("DC--Fun3()--c={}".format(c))
self.fun1(a) # Calling fun1() of BC1
self.fun2(b) # Calling fun2() of BC2
#main program
do=DC() # Object Creation
do.fun3(10,20,30)
-----------------------------------------------------------------------------------------------------------------
Example:
---------------------
#PolyMethodOverideEx4.py
class BC1:
def fun(self,a): # Original Method
print("BC1--Fun()--a={}".format(a))
class BC2:
def fun(self,b): # Original Method
print("BC2--Fun()--b={}".format(b))
class DC(BC2,BC1):
def fun(self,a,b,c): # Overridden method
print("DC--Fun()--c={}".format(c))
BC1.fun(self,a)
BC2.fun(self,b)
#main program
do=DC() # Object Creation
do.fun(10,20,30)
--------------------------------------------------------------------------------------------------------------------
Example:
---------------------
#PolyMethodOverideEx5.py
class BC1:
def __init__(self,a): # Original Constructor
print("BC1--Parameterized--a={}".format(a))
class BC2:
def __init__(self,b): # Original Constructor
print("BC2--Parameterized-b={}".format(b))
class DC(BC2,BC1):
def __init__(self):pass
def fun(self,a,b,c): # Separate method
print("DC--Fun()--c={}".format(c))
BC2.__init__(self,b)
BC1.__init__(self,a)
#main program
do=DC() # Object Creation
do.fun(10,20,30)
-------------------------------------------------------------------------------------------------------------
Example:
---------------------
#PolyMethodOverideEx6.py
class BC1:
def __init__(self,a): # Original Constructor
print("BC1--Parameterized--a={}".format(a))
class BC2:
def __init__(self,b): # Original Constructor
print("BC2--Parameterized-b={}".format(b))
class DC(BC2,BC1):
def __init__(self):
super().__init__(20)
BC1.__init__(self,10)
def fun(self,c): # Separate method
print("DC--Fun()--c={}".format(c))
#main program
do=DC() # Object Creation
do.fun(30)
----------------------------------------------------------------------------------------------------------------
Example:
---------------------
#WAPP which will calculate different figures area by using polymorphism.
#PolyMethodOverideEx7.py
class Circle:
def area(self,r):
self.ac=3.14*r**2
print("Area of Circle={}".format(self.ac))
class Square(Circle):
def area(self,s): # OVerridden Method
self.sa=s**2
print("Area of Square={}".format(self.sa))
class Rect(Square):
def area(self,l,b):
self.ar=l*b
print("Area of Rect={}".format(self.ar))
print("-"*50)
super().area(6)
Circle.area(self,3.4)
#main program
r=Rect()
r.area(10,12)
----------------------------------------------------------------------------------------------------------------
Example:
---------------------
#WAPP which will calculate different figures area by using polymorphism.
#PolyMethodOverideEx8.py
class Circle:
def area(self,r):
self.ac=3.14*r**2
print("Area of Circle={}".format(self.ac))
class Square(Circle):
def area(self,s): # OVerridden Method
self.sa=s**2
print("Area of Square={}".format(self.sa))
class Rect(Square):
def area(self,l,b):
self.ar=l*b
print("Area of Rect={}".format(self.ar))
print("-"*50)
super().area(float(input("Enter Side of Square:")))
Circle.area(self,float(input("Enter Radious of Circle:")))
#main program
r=Rect()
r.area(float(input("Enter Length:")),float(input("Enter Breadth:")) )
------------------------------------------------------------------------------------------------------------
Example:
---------------------
#WAPP which will calculate different figures area by using polymorphism.
#PolyMethodOverideEx9.py
class Circle:
def area(self,r):
self.ac=3.14*r**2
print("Area of Circle={}".format(self.ac))
class Square(Circle):
def area(self,s): # OVerridden Method
self.sa=s**2
print("Area of Square={}".format(self.sa))
class Rect(Circle):
def area(self,l,b):
self.ar=l*b
print("Area of Rect={}".format(self.ar))
print("-"*50)
super().area(float(input("Enter Radious of Circle:")))
#main program
r=Rect()
r.area(float(input("Enter Length:")),float(input("Enter Breadth:")) )
print("-"*50)
s=Square()
s.area(float(input("Enter Side of Square:")))
=================================================
Index Object Oriented Principles or Features or Concepts
=================================================
Index:
---------
=>What are the advantages of OOPs
=>List of Object Oriendted Principles
1. Classes
2. Objects
3. Data Encapsulation
4. Data Abstraction
5. Inheritance
6. Polymorphism
7. Message Passing
--------------------------------------------------------------------
1. Classes
=>Importaance and purpose of Classes concept
=>Syntax for Defining Class
=>Types of Data Members
a) Instance Data Members
b) Class Level Data Members
=>Types of Methods
a) Instance Method
b) Class Level Method
c) Static Method
=>What is "self" and "cls"
=>Programming Examples
2. Object
=>Importaance and purpose of Object Concept
=>Syntax for creating Object
=>Programming Examples
=>Programples related to pickling and Data base communication with Classes and objects.
------------------------------------------------------------------------------------------------------
=>Constructors in OOPs
=>Importance and purpose of Constructors
=>Types of Constructors
a) Default Constructors
b) Parameterized Constructors
=>Rules for Constructors
=>Programming Examples
--------------------------------------------------------------------------
=>Detstructrors in OOPs with Garbage Collector
=>Importance and purpose of Detstructrors
=>Syntax for defining Detstructrors
=>Internal flow of Detstructrors
=>relation between Detstructrors and Garbage Collector
=>gc module
--------------------------
3. Data Encapsulation and Data Abstraction
=>Importance and purpose of Data Encapsulation
=>Importaance and purpose of Data Abstraction
=>Implementation of data encapsulation and Data Abstraction
=>Programming Examples
--------------------------------------------------
5. Inheritance
=>Importaance and purpose of Inheritance
=>Types of Inheritances
a) single
b) multi level
c) hierarchical
d) multiple
e) Hybrid
=>Syntax for Inheritance
=>Programming Examples
--------------------------------------------------
Method Overriding in OOPs
=>Importaance and purpose of Method Overriding
=>memory management in Method Overriding
=>Programming Examples
----------------------------------------------
6.Polymorphism
----------------------------------------------
=>Importaance and purpose of Polymorphism
=>Difference between Polymorphism and Inheritance
=>Method Overring with Polymorphism
=>super() and class name approaches in Polymorphism
=>Programming Examples
-----------------------------------------------------------------------
Numpy
------------------
Introduction to Numpy
Advantages of Numpy
Differences between list and ndarray of numpy
------------------------------------------------------------------------------------------------
====================================================
Advantages of using NumPy
====================================================
-------------------------------------
Need of NumPy:
-------------------------------------
=>With the revolution of data science, data analysis libraries like NumPy, SciPy, Scikit, Pandas, etc.
have seen a lot of growth. With a much easier syntax than other programming languages, python is
the first choice language for the data scientist.
=>NumPy provides a convenient and efficient way to handle the vast amount of data. NumPy is also
very convenient with Matrix Operations and data reshaping. NumPy is fast which makes it reasonable
to work with a large set of data.
---------------------------------------------------------------------------
The advantages of Numpy Programming are:
---------------------------------------------------------------------------
1) With Numpy Programming, we can deal with Arrays such 1-D, 2-D and Multi Dimensional
Arrays.
2) NumPy maintains minimal memory for large sets of data:
3) Numpy provides Fast in Performing Operations bcoz internally its data is available at
same address.
4) NumPy performs array-oriented computing.
5) It efficiently implements the multidimensional arrays.
6) It performs scientific computations.
7) It is capable of performing reshaping the data stored in multidimensional arrays.
8) NumPy provides Many in-built functions for Various Complex Mathematical Operations such as
statistical, financial, trigonometric Operations etc.
==========================================
Numpy
==========================================
Introduction to Numpy:
-------------------------------------
=>Numpy stands for Numerical Python.
=>Numpy is one of the pre-defined third party module / Library and numpy module is not a pre-
defined module in Python Language.
=>To use numpy as a part of our python program, we must install numpy
module explicitly by using a tool called pip and it present in
(C:\Users\nareshit\AppData\Local\Programs\Python\Python39\Scripts)
=>Syntax for installing any module:
=>To use numpy as part of our program, we must import numpy module.
=>A Numpy module is a collection of Variables, Functions and Classes.
History of Numpy:
------------------------------
=>Numpy was developed by studying existing module called "Numeric Library"(origin for
development of numpy module)
=>The Numeric Library was developed by JIM HUNGUNIAN
=>The Numeric Library was not able to solve complex maths calculations.
=>Numpy module developed by TRAVIS OLIPHANT
=>Numpy Module developed in the year 2005
=>Numpy Module developed in C and PYTHON languages.
===================================================
Python Traditional List VS Numpy Module
===================================================
Similarities of python Traditional List VS Numpy Module:
-----------------------------------------------------------------------------------------
=>An object of list used to store multiple values of same type or different type and both types (unique
+duplicates) in single object.
=>In Numpy Programming, the data is organized in the object of "ndarray", which is one of the pre-
defined class in numpy module. Hence an object of ndarray can store same type or different type and
both types (unique +duplicates) in single object.
=>The objects of ndarray and list are mutable (changes can takes place)
-------------------------------------------------------------------------------------------------------------------------
Differences between Python Traditional List and ndarray object of Numpy Module:
-------------------------------------------------------------------------------------------------------------------------
=>An object of list contains both homogeneous and heterogeneous values where as an object of
ndarray of numpy can store only similar type of values(even we store different values, internally they
are treated as similar type by treating all values of type "object" ).
=>On the object of list, we can't perform Vector Operations. where as on the object of ndarray, we
can perform Vector based operations.
=>In large sampling of data, List based applications takes more memory space where ndarray object
takes less memory space.
=>List based applications are not effiecient bcoz list object values takes more time to extract or
retrive ( they are available at different Address) where as numpy based applications are efficient bcoz
of ndarray object values takes less to time to extract or retrive( they are available at same Address).
=>List object can't perform complex mathematical operations where as an object of ndarray can
perform complex mathematical operations.
=================================================
Number of approaches to create an object of ndarray
=================================================
=>In numpy programming, we have 6 approaches to create an object of ndarray. They are
1. array()
2. arange()
3. zeros()
4. ones()
5. full()
6. identity()
-----------------------------------------------------------------------------------------------------
1) array():
----------------------------------
=>This Function is used for converting Traditional Python Objects into ndrray object.
=>Syntax:- varname=numpy.array( Object,dtype )
Here var name is an object of <class,ndarray>
here array() is pre-defined function of numpy module used for converting
Traditional Python Objects into ndrray object.
object represents any Traditional Python Objects
dtype represents any numpy data type such as int8,int16,int32,float16, float 32,
float64,....etc
Examples:
------------------
>>> import numpy as np
>>> l1=[10,20,30,40,50,60]
>>> print(l1,type(l1))-----------------[10, 20, 30, 40, 50, 60] <class 'list'>
>>> a=np.array(l1)
>>> print(a,type(a))----------------[10 20 30 40 50 60] <class 'numpy.ndarray'>
>>> t=(10,20,30,40,50,60,70)
>>> print(t,type(t))--------------(10, 20, 30, 40, 50, 60, 70) <class 'tuple'>
>>> a=np.array(t)
>>> print(a,type(a))--------------[10 20 30 40 50 60 70] <class 'numpy.ndarray'>
>>> d1={10:1.2,20:4.5,30:6.7}
>>> a=np.array(d1)
>>> a----array({10: 1.2, 20: 4.5, 30: 6.7}, dtype=object)
---------------------------------------------------------------------------------------
>>> t=(10,20,30,40,50,60)
>>> a=np.array(t)
>>> a--------------array([10, 20, 30, 40, 50, 60])
>>> a.ndim------------1
>>> a.dtype----------dtype('int32')
>>> a.shape-------------(6,)
>>> b=a.reshape(3,2)
>>> c=a.reshape(2,3)
>>> b--------------
array([[10, 20],
[30, 40],
[50, 60]])
>>> c
array([[10, 20, 30],
[40, 50, 60]])
>>> print(b,type(b))
[[10 20]
[30 40]
[50 60]] <class 'numpy.ndarray'>
>>> print(c,type(c))
[[10 20 30]
[40 50 60]] <class 'numpy.ndarray'>
>>> b.ndim-------------2
>>> c.ndim------------2
>>> b.shape---------------(3, 2)
>>> c.shape-------------(2, 3)
>>> d=a.reshape(3,3)-------ValueError: cannot reshape array of size 6 into shape (3,3)
---------------------------------------------------------------------------------------------------------------------------
-
>>> t1=((10,20),(30,40))
>>> print(t1,type(t1))--------------((10, 20), (30, 40)) <class 'tuple'>
>>> a=np.array(t1)
>>> a
array([[10, 20],
[30, 40]])
>>> a.ndim----------2
>>> a.shape----------(2, 2)
------------------------------------------------------------------------------------------------------------
>>> t1=( ((10,20,15),(30,40,25)),( (50,60,18),(70,80,35) ))
>>> print(t1,type(t1))
(((10, 20, 15), (30, 40, 25)), ((50, 60, 18), (70, 80, 35))) <class 'tuple'>
>>> a=np.array(t1)
>>> a
array([[[10, 20, 15],
[30, 40, 25]],
[[50 60 18]
[70 80 35]]]
>>> a.ndim
3
>>> a.shape
(2, 2, 3)
>>> b=a.reshape(4,3)
>>> b
array([[10, 20, 15],
[30, 40, 25],
[50, 60, 18],
[70, 80, 35]])
>>> c=a.reshape(3,4)
>>> c
array([[10, 20, 15, 30],
[40, 25, 50, 60],
[18, 70, 80, 35]])
>>> d=a.reshape(3,2,2)
>>> d
array([[[10, 20],
[15, 30]],
[[40, 25],
[50, 60]],
[[18, 70],
[80, 35]]])
>>> d[0]
array([[10, 20],
[15, 30]])
>>> d[1]
array([[40, 25],
[50, 60]])
>>> d[2]
array([[18, 70],
[80, 35]])
>>>
-----------------------------------------------------------------------------------
2. arange():
------------------------------------------------------------------------------------
Syntax1:- varname=numpy.arange(Value)
Syntax2:- varname=numpy.arange(Start,Stop)
Syntax3:- varname=numpy.arange(Start,Stop,Step)
=>Here var name is an object of <class,ndarray>
Examples:
-----------------
>>> import numpy as np
>>> a=np.arange(10)
>>> a-----------array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.ndim--------1
>>> a=np.arange(50,62)
>>> print(a,type(a))---[50 51 52 53 54 55 56 57 58 59 60 61] <class 'numpy.ndarray'>
>>> a.ndim------1
>>> a=np.arange(10,23,2)
>>> a-----array([10, 12, 14, 16, 18, 20, 22])
>>> a=np.arange(10,22,2)
>>> a--------array([10, 12, 14, 16, 18, 20])
>>> b=a.reshape(2,3)
>>> c=a.reshape(3,2)
>>> b-----
array([[10, 12, 14],
[16, 18, 20]])
>>> c
array([[10, 12],
[14, 16],
[18, 20]])
>>> b.ndim------ 2
>>> c.ndim------- 2
>>> b.shape-----(2, 3)
>>> c.shape-----(3, 2)
>>> l1=[ [[10,20],[30,40]], [[15,25],[35,45]] ]
>>> l1----------[[[10, 20], [30, 40]], [[15, 25], [35, 45]]]
>>> a=np.arange(l1)----------TypeError: unsupported operand type(s) for -: 'list' and 'int'
==================================================================
3. zeros():
------------------------
=>This Function is used for building ZERO matrix either with 1-D or 2-D or n-D
=>Syntax: varname=numpy.zeros(shape,dtype)
[[0, 0],
[0, 0],
[0, 0]]])
[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]]])
>>> a.reshape(2,3,2)
array([[[0, 0],
[0, 0],
[0, 0]],
[[0, 0],
[0, 0],
[0, 0]]])
>>> a.reshape(2,2,3)
array([[[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0]]])
----------------------------------------------------------------------------
>>> import numpy as np
>>> a=np.zeros((3,3),dtype=int)
>>> a
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a=np.zeros((2,3))
>>> a
array([[0., 0., 0.],
[0., 0., 0.]])
>>> a=np.zeros((2,3),int)
>>> a
array([[0, 0, 0],
[0, 0, 0]])
>>> a=np.zeros((3,2,3),dtype=int)
>>> a
array([[[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0]]])
>>> print(a,type(a))
[[[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]]] <class 'numpy.ndarray'>
---------------------------------------
4. ones()
---------------------------------------
=>This Function is used for building ONEs matrix either with 1-D or 2-D or n-D
=>Syntax: varname=numpy.ones(shape,dtype)
Examples:
-----------------------------
>>> import numpy as np
>>> a=np.ones(10)
>>> print(a,type(a))----------[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] <class 'numpy.ndarray'>
>>> a=np.ones(10,dtype=int)
>>> print(a,type(a))-------------[1 1 1 1 1 1 1 1 1 1] <class 'numpy.ndarray'>
>>> a.shape-----------(10,)
>>> a.shape=(5,2)
>>> a
array([[1, 1],
[1, 1],
[1, 1],
[1, 1],
[1, 1]])
>>> a.ndim-------------- 2
>>> a.shape------------ (5, 2)
>>> a.shape=(2,5)
>>> a
array([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
>>> a.shape----------------------(2, 5)
>>>
>>> a=np.ones((3,4),dtype=int)
>>> a
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
>>> a=np.ones((4,3),dtype=int)
>>> print(a,type(a))
[[1 1 1]
[1 1 1]
[1 1 1]
[1 1 1]] <class 'numpy.ndarray'>
>>> a.shape----------(4, 3)
>>> a.shape=(3,2,2)
>>> a
array([[[1, 1],
[1, 1]],
[[1, 1],
[1, 1]],
[[1, 1],
[1, 1]]])
>>> a=np.ones((4,3,3),dtype=int)
>>> a
array([[[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]]])
>>> a[0][0][0]-----------1
>>> a[0,0,0]-----------1
>>> a[0][0,0]------------1
================================================================
5) full()
-------------------------
=>This is function is used for building a matrix by specifying fill value either 1-D or 2-D or n-D
=>Syntax:-
varname=numpy.full(shape,fill_value,dtype)
=>varname is an obejct of <class, numpy.ndarray>
=>Here Shape can be 1-D(number of Zeros) or 2-D(Rows,Cols) or n-D( Number of
Matrices,Number of Rows, Number of Columns)
=>fill_value can be any number of programmer choice
Examples:
-------------------
>>> a=np.full(3,1)
>>> a---------array([1, 1, 1])
>>>print(type(a))--------<class,numpy.ndarray>
>>> a=np.full(3,9)
>>> a------------array([9, 9, 9])
>>> a=np.full(6,8)
>>> a-------------array([8, 8, 8, 8, 8, 8])
>>> a.shape=(3,2)
>>> a
array([[8, 8],
[8, 8],
[8, 8]])
>>> a=np.full(6,9)
>>> a----------array([9, 9, 9, 9, 9, 9])
>>> a.reshape(2,3)
array([[9, 9, 9],
[9, 9, 9]])
>>> a=np.full((3,3),9)
>>> a
array([[9, 9, 9],
[9, 9, 9],
[9, 9, 9]])
>>> a=np.full((2,3),6)
>>> a
array([[6, 6, 6],
[6, 6, 6]])
>>> a.reshape(3,2)
array([[6, 6],
[6, 6],
[6, 6]])
>>> a=np.full((3,3,3),7)
>>> a
array([[[7, 7, 7],
[7, 7, 7],
[7, 7, 7]],
[[7, 7, 7],
[7, 7, 7],
[7, 7, 7]],
[[7, 7, 7],
[7, 7, 7],
[7, 7, 7]]])
==================================================================
6) identity():
----------------------------------
=>This function always bulid Identity or unit matrix
=>Syntax:- varname=numpy.identity(N,dtype)
=>Here N represents Either we can take Rows or Columns and PVM takes as NXN Matrix (Square
Matrix--Unit or Identity)
Examples:
--------------------------
>>> import numpy as np
>>> a=np.identity(3,dtype=int)
>>> print(a,type(a))-------------
[[1 0 0]
[0 1 0]
[0 0 1]] <class 'numpy.ndarray'>
>>> a=np.identity(5,dtype=int)
>>> print(a,type(a))
[[1 0 0 0 0]
[0 1 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]] <class 'numpy.ndarray'>
===================================X===================================
Indexing and Slicing Operations on ndarray -1-D 2-D and n-D Arrays
Advanced Indexing and Slicing Operations on ndarray -1-D 2-D and n-D Arrays
Filtering the data from ndArray
--------------------------------------------------------------------------------------------------------------------------
=================================================
Numpy---Advanced Indexing
=================================================
==>If we want to access multiple elements, which are not in order (arbitrary elements) of 1D,2D and
N-D arrays we must use the concept of Advanced Indexing.
=>If we want access the elements based on some condition then we can't use basic indexing and
Basic Slicing Operations. To fullfill such type of requirements we must use advanced Indexing.
--------------------------------------------------------------------
=>Accessing Multiple Arbitrary Elements ---1D :
---------------------------------------------------------------------
=>Syntax:- ndarrayname [ x ]
=>Here 'x' can be either ndarray or list which represents required indexes of arbitrary elements.
----------------
Examples:
------------------
>>> lst=[10,20,30,40,50,60,70,80,90]
>>> a=np.array(lst)
>>> print(a)----------------[10 20 30 40 50 60 70 80 90]
#access 10 30 and 80 elements
# here indexes of 10 30 and 80 are 0 2 7
>>>lst=[0,2,7] here [0,2,7] are indexes of 10 30 and 80
>>> indexes=np.array(lst) # here lst converted into ndarray object
>>> print(indexes)---------[0 2 7]
>>> print(a[indexes])--------------[10 30 80]
(OR)
>>> ind=[0,2,7] # prepare the list of indexes of arbitray elements(10,30,80) of ndarray and pass to
ndarray
>>> print(a[ind]) -----------[10 30 80]
Examples:
---------------------
Q1-->Access 20 30 80 10 10 30
>>> lst=[10,20,30,40,50,60,70,80,90]
>>> a=np.array(lst)
>>> print(a)----------------[10 20 30 40 50 60 70 80 90]
>>> ind=[1,2,7,0,0,2] # [1,2,7,0,0,2] are the indexes of 20 30 80 10 10 30
>>> print(a[ind])----------------[20 30 80 10 10 30]
-----------------------------------------------------------------------------------------------------------
=>Accessing Multiple Arbitrary Elements ---2D :
----------------------------------------------------------------------------------------------------------
=>Syntax:- ndarrayobj[ [row indexes],[column indexes] ]
Examples:-
---------------
>>>import numpy as np
>>>mat=np.array([ [1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16] ] )
>>> print(mat)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
----------------
Examples:
---------------
>>>import numpy as np
>>>l1=[ [ [1,2,3,4],[5,6,7,8],[9,10,11,12] ],[ [13,14,15,16],[17,18,19,20],[21,22,23,24] ] ]
>>>mat3d=np.array(l1)
>>>print(mat3d)
>>> print(mat3d)
[[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[13 14 15 16]
[17 18 19 20]
[21 22 23 24]]]
>>> mat3d.ndim
3
>>> mat3d.shape
(2, 3, 4)
----------------------------------------
Q1) Access the elements 1 14 24
Ans:- mat3d[ [0,1,1], [0,0,2], [0,1,3] ]
a.shape=(2,2,2,2)
print(a)
[[[[10 20]
[30 40]]
[[50 60]
[70 80]]]
[[[15 25]
[35 45]]
[[55 65]
[75 85]]]]
=================================================
Numpy---Basic Indexing
=================================================
==>If we want to access Single element of 1D,2D and N-D arrays we must use the concept of Basic
Indexing.
--------------------------------------------------------------------
=>Accessing Single Element 1D-Array :
---------------------------------------------------------------------
=>Syntax:- ndarrayname [ Index ]
-----------------------------------------------------------------------------------------------------------
=>Accessing single Element of 2D:
----------------------------------------------------------------------------------------------------------
=>Syntax:- ndarrayobj[ row index,column index]
----------------
Examples:-
---------------
>>>import numpy as np
>>> a=np.array([10,20,30,40,50,60])
>>> b=a.reshape(2,3)
>>> b
array([[10, 20, 30],
[40, 50, 60]])
>>> b[0,0]
10
>>> b[0,1]
20
>>> b[1,2]
60
======================================================================
=>Accessing single Element of 3D :
------------------------------------------------------------------------------------------------------------------------
Syntax:- ndarrayobj[ Index of matrix , row index , column index ]
-------------
Examples:
---------------
>>> a=np.array([10,20,30,40,50,60,70,80])
>>> b=a.reshape(2,2,2)
>>> b
array([[[10, 20],
[30, 40]],
[[50, 60],
[70, 80]]])
>>> b[0,0,0]-----------10
>>> b[-1,0,0]---------50
>>> b[-2,1,1]---------40
-------------------------------------------------------------------
=======================================================
Numpy---Indexing and Slicing Operations of 1D,2D and 3D array
=======================================================
------------------------------------
1D Arrays Slicing:
------------------------------------
Syntax:- 1dndrrayobj[begin:end:step]
-----------------------
Examples:
-----------------------
>>> a=np.array([10,20,30,40,50,60,70])
>>> a------------array([10, 20, 30, 40, 50, 60, 70])
>>> a[::-1]-----------array([70, 60, 50, 40, 30, 20, 10])
>>> a[::]-----------array([10, 20, 30, 40, 50, 60, 70])
------------------------------------
2D Arrays Slicing:
------------------------------------
Syntax:- ndrrayobj[i,j]
here 'i' represents Row Index
here 'j' represents Column Index
--------------------------------------------------------------------
Examples:
--------------------------------------------------------------------
>>> a=np.array([[10,20,30],[40,50,60]])
>>> a
array([[10, 20, 30],
[40, 50, 60]])
>>> a[0,0]
10
>>> a[0:,0:1]
array([[10],
[40]])
>>> a[0:,1:2]
array([[20],
[50]])
>>> a[1:,:]
array([[40, 50, 60]])
===============================================================
3D Arrays Slicing
-----------------------------
Syntax:- 3dndrrayobj[i,j,k]
[[13 14 15]
[16 17 18]
[19 20 21]]]
>>> arr2.ndim
3
>>> arr2.shape
(2, 3, 3)
>>> arr2[:,:,0:1]
array([[[ 1],
[ 4],
[ 7]],
[[13],
[16],
[19]]])
>>> arr2[:,:,:1]
array([[[ 1],
[ 4],
[ 7]],
[[13],
[16],
[19]]])
>>> arr2[: , 0:2, 1:3]
array([[[ 2, 3],
[ 5, 6]],
[[14, 15],
[17, 18]]])
>>> arr2[: , :2, 1:]
array([[[ 2, 3],
[ 5, 6]],
[[14, 15],
[17, 18]]])
-----------------------------------------------------------------
===============================================================
Numpy--selecting the elements based on condition
(OR)
Creating Filter Directly From ndArray
================================================================
=>To select any element from ndarray object, we have two approaches. They are
-------------------
Approach-1:
-------------------
=>Prepare Boolean Array ( It contains True or False. True represents Condition
satisfied and False represents Condition not satisfied]
=>Pass the Boolean Array to the ndarray object. so that we can get those elements from ndarray
which satisfies with the entry True(or) we can get those elements from ndarray corresponding True
entries of Boolean array.
-------------------
Approach-2:
-------------------
=>In this approach, we directly pass Boolean array values to the ndarray for getting required elements
based on condition.
=>Syntax:- varname=ndrrayobj.copy()
(OR)
ndarrayobj2=numpy.copy(ndarrayobj1)
=>The view does not own the data and any changes made to the view will affect the original array,
and any changes made to the original array will affect the view.
=>Syntax:- varname=ndrrayobj.view()
ERROR : varname=ndrrayobj.view()
------------------------------------------------------------------------------------------------------------
COPY:
---------------
Example
------------------
# Make a copy, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr) # [42 2 3 4 5]
print(x) # [1 2 3 4 5]
---------------------------------------------------------------------------------------------------------------------------
NOTE: The copy SHOULD NOT be affected by the changes made to the original array.
---------------------------------------------------------------------------------------------------------------------------
VIEW:
-----------------
Example
------------------
#Make a view, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr) # [42 2 3 4 5]
print(x) # [42 2 3 4 5]
------------------------------------------------------------------------------------------------------------------------
NOTE : The view SHOULD be affected by the changes made to the original array.
------------------------------------------------------------------------------------------------------------------------
# Make Changes in the VIEW:
------------------
Example
------------------
# Make a view, change the view, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
x[0] = 31
print(arr) # [31 2 3 4 5]
print(x) # [31 2 3 4 5]
-----------------------------------------------------------------------------------------------------------
=>In the case append(), view() does not reflect the changes
------------------------------------------------------------------------------------------------------------
-------------------------------------------------
NumPy Sorting Arrays
--------------------------------------------------
=>Sorting is nothing arranging the elements in an ordered sequence.
=>Ordered sequence is any sequence that has an order corresponding to elements, like numeric or
alphabetical, ascending or descending.
=>The NumPy ndarray object has a function called sort(), that will sort a specified array.
Examples:
-------------------
import numpy as np
arr = np.array([3, 2, 0, 1])
print(np.sort(arr)) # [0 1 2 3]
----------------------------------------------------
import numpy as np
arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr)) # ['apple' 'banana' 'cherry']
-----------------------------------------------------
import numpy as np
arr = np.array([True, False, True])
print(np.sort(arr)) # [False True True]
-------------------------------------------------------
Sorting a 2-D Array
--------------------------------------------------------
If you use the sort() method on a 2-D array, both columns and Rows of nd array will be sorted.
-------------------
Examples:
-------------------
import numpy as np
arr = np.array([[3, 2, 4], [5, 0, 1]])
print(np.sort(arr))
#output
[[2 3 4]
[0 1 5]]
--------------------------------------------------------------------------------------------------
a=np.array([110, 20, -30, 40, 50, 160, 7, 8, 90])
print(a)
np.sort(a,axis=0) # ColumnWise
array([[ 7, 8, -30],
[ 40, 20, 90],
[110, 50, 160]])
-----------------------------------------------------------
print(a)
array([[110, 20, -30],
[ 40, 50, 160],
[ 7, 8, 90]])
Examples:
------------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.subtract(a,b)
>>> c
array([[ 9, 18],
[27, 36]])
-----------------------------------
>>> d=a-b # we used operator - instead of subtract()
>>> d
array([[ 9, 18],
[27, 36]])
===================================
c) multiply():
-----------------------
Syntax:- varname=numpy.multiply(ndarrayobj1, ndarrayobj2)
=>This function is used for performing element-wise multiplication of ndarrayobj1, ndarrayobj2 and
result can be displayed
Examples:
------------------
>>> l1=[[1,2],[3,4]]
>>> l2=[[5,6],[4,3]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[1, 2],
[3, 4]])
>>> b
array([[5, 6],
[4, 3]])
>>> c=np.multiply(a,b)
>>> c
array([[ 5, 12],
[12, 12]])
-----------------------------------------------
>>> e=a*b # we used operator * instead of multiply()
>>> e
array([[ 5, 12],
[12, 12]])
------------------------------------------
d) dot()
------------------
=>To perform Matrix Multiplication, we use dot()
=>This function is used for performing actual matrix multiplication of ndarrayobj1, ndarrayobj2 and
result can be displayed
Examples:
-----------------
>>> l1=[[1,2],[3,4]]
>>> l2=[[5,6],[4,3]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[1, 2],
[3, 4]])
>>> b
array([[5, 6],
[4, 3]])
>>> d=np.dot(a,b)
>>> d
array([[13, 12],
[31, 30]])
-----------------------------------------------------------------------------
e) divide()
-----------------------------------
Syntax:- varname=numpy.divide(ndarray1,ndarry2)
=>This function is used for performing element-wise division of ndarrayobj1, ndarrayobj2 and result
can be displayed
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.divide(a,b)
>>> c
array([[10., 10.],
[10., 10.]])
---------------------------------------------------------------
>>> d=a/b # we used operator / instead of divide()
>>> d
array([[10., 10.],
[10., 10.]])
---------------------------------------------------------------------------------------------
f) floor_divide()
-----------------------------------
Syntax:- varname=numpy.floor_divide(ndarray1,ndarry2)
=>This function is used for performing element-wise floor division of ndarrayobj1, ndarrayobj2 and
result can be displayed
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.floor_divide(a,b)
>>> c
array([[10, 10],
[10, 10]])
---------------------------------------------------------------
>>> d=a//b # we used operator // instead of floor_divide()
>>> d
array([[10, 10],
[10, 10]])
--------------------------------------------------------------------------------------------------------------------
g) mod()
-------------------------------
Syntax:- varname=numpy.mod(ndarray1,ndarry2)
=>This function is used for performing element-wise modulo division of ndarrayobj1, ndarrayobj2
and result can be displayed
--------------------
Examples:
---------------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>> c=np.mod(a,b)
>>> c
array([[0., 0.],
[0., 0.]])
------------------------------------------------------------------------
=>We can also do with operator %
>>> e=a%b
>>> e
array([[0, 0],
[0, 0]], dtype=int32)
-----------------------------------------------------------------------------------------------------
h) power():
---------------------------------------
Syntax:- varname=numpy.power(ndarray1,ndarry2)
=>This function is used for performing element-wise exponential of ndarrayobj1, ndarrayobj2 and
result can be displayed
---------------------------------------
>>> l1=[[10,20],[30,40]]
>>> l2=[[1,2],[3,4]]
>>> a=np.array(l1)
>>> b=np.array(l2)
>>> a
array([[10, 20],
[30, 40]])
>>> b
array([[1, 2],
[3, 4]])
>>>c=np.power(a,b)
>>>print(c)
array([[ 10, 400],
[ 27000, 2560000]],
----------------------------------------------------------------------------------------------------
Example:
---------------------
>>> f=a**b # Instead of using power() we can use ** operator
>>> f
array([[ 10, 400],
[ 27000, 2560000]], dtype=int32)
===========================================
Numpy--Statistical Operations
===========================================
=>On the object of ndarray, we can the following Statistical Operations .
a) amax()
b) amin()
c) mean()
d) median()
e) var()
f) std()
=>These operation we can perform on the entire matrix and we can also perform on column wise
(axis=0) and Rowwise (axis=1)
a) amax():
-------------------
=>This functions obtains maximum element of the entire matrix.
=>Syntax1:- varname=numpy.amax(ndarrayobject)
Examples:
-------------------
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> max=np.amax(A)
>>> cmax=np.amax(A,axis=0)
>>> rmax=np.amax(A,axis=1)
>>> print("Max element=",max)-----------Max eleemnt= 4
>>> print("Column Max eleemnts=",cmax)---Column Max eleemnts= [4 4 3]
>>> print("Row Max eleemnts=",rmax)---Row Max eleemnts= [3 4 4]
-----------------------------------------------------------------------------------------------------
b) amin():
-------------------
=>This functions obtains minmum element of the entire matrix.
=>Syntax1:- varname=numpy.amin(ndarrayobject)
Examples:
-----------------
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> m=np.mean(A)
>>> cm=np.mean(A,axis=0)
>>> rm=np.mean(A,axis=1)
>>> print("Mean=",m)---------Mean= 2.4444444444444446
>>> print("Column Mean=",cm)-----Column Mean= [2.66666667 2.66666667 2. ]
>>> print("Row Mean=",rm)---Row Mean= [ 2. 2.33333333 3. ]
------------------------------------------------------------------------------------------------------
d) median()
---------------------
=>This is used for calculating / obtaining median of entire matrix elements.
=>Median is nothing but sorting the given data in ascending order and select middle element.
=>If the number sorted elements are odd then centre or middle element becomes median.
=>If the number sorted elements are even then select centre or middle of two elements, add them and
divided by 2 and that result becomes median.
Syntax1:- varname=numpy.median(ndarrayobject)
Syntax2:- varname=numpy.median(ndarrayobject,axis=0)
Syntax3:- varname=numpy.median(ndarrayobject,axis=1)
Examples:
--------------------
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> md=np.median(A)
>>> cmd=np.median(A,axis=0)
>>> rmd=np.median(A,axis=1)
>>> print("Median=",md)----Median= 2.0
>>> print("Column Median=",cmd)---Column Median= [3. 2. 2.]
>>> print("Row Median=",rmd)------Row Median= [2. 2. 3.]
>>> l1=[[2,3],[4,1]]
>>> A=np.array(l1)
>>> print(A)
[[2 3]
[4 1]]
>>> md=np.median(A)
>>> cmd=np.median(A,axis=0)
>>> rmd=np.median(A,axis=1)
>>> print("Median=",md)---Median= 2.5
>>> print("Column Median=",cmd)---Column Median= [3. 2.]
>>> print("Row Median=",rmd)---Row Median= [2.5 2.5]
-----------------------------------------------------------------------------------------
e) var():
-------------
Variance= sqr(mean-xi) / total number of elements
here 'xi' represents each element of matrix.
------------------
Syntax1:- varname=numpy.var(ndarrayobject)
Syntax2:- varname=numpy.var(ndarrayobject,axis=0)
Syntax3:- varname=numpy.var(ndarrayobject,axis=1)
--------------------
Examples:
--------------------
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> vr=np.var(A)
>>> cvr=np.var(A,axis=0)
>>> rvr=np.var(A,axis=1)
>>> print("Variance=",vr)----Variance= 1.1358024691358024
>>> print("Column Variance=",cvr)---Column Variance= [1.55555556 0.88888889
0.66666667]
>>> print("Row Variance=",rvr)---Row Variance= [0.66666667 1.55555556 0.66666667]
--------------------------------------------------------------
f) std()
------------------
standard deviation=sqrt(var)
Syntax1:- varname=numpy.std(ndarrayobject)
Syntax2:- varname=numpy.std(ndarrayobject,axis=0)
Syntax3:- varname=numpy.std(ndarrayobject,axis=1)
-------------------------------
Examples:
----------------
>>> l1=[[1,2,3],[4,2,1],[3,4,2]]
>>> A=np.array(l1)
>>> print(A)
[[1 2 3]
[4 2 1]
[3 4 2]]
>>> vr=np.var(A)
>>> cvr=np.var(A,axis=0)
>>> rvr=np.var(A,axis=1)
>>> print("Variance=",vr)---Variance= 1.1358024691358024
>>> print("Column Variance=",cvr)---Column Variance= [1.55555556 0.88888889
0.66666667]
>>> print("Row Variance=",rvr)---Row Variance= [0.66666667 1.55555556 0.66666667]
--------------------------------------------------------------------------------------------------
>>> sd=np.std(A)
>>> csd=np.std(A,axis=0)
>>> rsd=np.std(A,axis=1)
>>> print("std=",sd)---std= 1.0657403385139377
>>> print(" column std=",csd)--- column std= [1.24721913 0.94280904 0.81649658]
>>> print("Row std=",rsd)--Row std= [0.81649658 1.24721913 0.81649658]
==========================X=====================================
---------------------------------------------------
Adding Elements in Numpy Array
-------------------------------------------------
Numpy module in python, provides a function to numpy.append() to add an element in a numpy array.
Syntax: Varname=numpy.append( ndarrayobj, value)
Example:
-----------------
import numpy as np
#Create a Numpy Array of integers
arr = np.array([11, 2, 6, 7, 2])
# Add / Append an element at the end of a numpy array
new_arr = np.append(arr, 10)
print('New Array: ', new_arr)
print('Original Array: ', arr)
----------------------------------------------------------------------
Inserting elements in numpy
----------------------------------------------------------------------
Numpy module in python, provides a function numpy.insert() to insert the element in ndarray at
particular Index.
Syntax: varname=np.insert( (ndarray , index, value)
Example.
-------------------
import numpy as np
a=np.array([10,20,30,40])
a=np.array([10,20,30,40])
b=np.insert(a,1,35)
print(a)# array([10, 35, 20, 30, 40])
---------------------------------------------------------------------------------------------------
deleting element(s) from Numpy Array
---------------------------------------------------------------------------------------------------
Numpy module in python, provides a function numpy.delete() to delete elements.
Syntax: varname=np.delete( ndaary,index ) # Delete element at index
Syntax: varname=np.delete( ndaary,[index1,..index-n] ) # Delete element at indices
Example.
----------------
import numpy as np
arr = np.array([4,5,6,7,8,9,10,11])
arr = np.delete(arr, 2)
print(arr)
arr = np.array([4, 5, 6, 7, 8, 9, 10, 11])
# Delete element at index positions 1,2 and 3
arr = np.delete(arr, [1,2,3])
---------------------------------------------------------------------