Chapter 5
Chapter 5
class Test1:
def sayHello(self):
print(“Hello from class Test1”)
def sayHi(self)
print(“Hi from class Test1”)
class Test2:
x=5
y=10
def sayHello(self):
print("Hello from class Test")
def sayHi(self):
print("Hi from class Test")
Again note the indents for data-members and member-functions. The data must be initialized.
(Because Python don't allow explicit declaration of data-members)
And the scope of data-members upto that class.
Unlike other languages, to use data-members in member-function we must take help of parameter '
self ’ which is almost like 'this pointer ' of C++ and 'this' of Java.)
class Test3:
x=5
def accept_x(self):
print("Enter value for x")
self. x = int(input())
def show_x(self):
print("x =",self.x)
def reset_x(self):
self.x =5
Line-2 declares data-member 'x' and it was accessed in line-5, line-7 and line-9 by using parameter
'self’ in three different member-functions. We can call these member functions in required order by
using object from anywhere.
For example, to declare object of above class Test3, then it will be as follows.
t= Test3()
Don't forget the parenthesis ( ) with class name Test3. If parenthesis is not applied, then it won't be
object, but instead it will be a reference. And a reference will not be helpful to call/use/access
members of class Test3.
After declaring object, we can work with data-members and member-functions by using object name
and dot operator (.). Refer following complete example.
class Test2:
x=5
y=10
def sayHello(self):
print("Hello from class Test")
def sayHi(self):
print("Hi from class Test")
t=Test2()
print("x=", t.x)
print("y=", t.y)
t.sayHello();
t.sayHi();
Output:
x= 5
y= 10
Hello from class Test
Hi from class Test
In similar way, we can declare any number of objects of a class and works on its members. Example:
t1=Test2()
t2=Test2()
t3=Test2()
OR
t1, t2, t3 = Test2( ), Test2( ), Test2( )
class Test3:
x=5
def accept_x(self):
print("Enter value for x")
self.x=int(input())
def show_x(self):
print("x = ",self.x)
def reset_x(self):
self.x =5
print("x = ",self.x)
t1=Test3()
t1.accept_x()
t1.show_x()
t1.reset_x();
If we did not use parameter self in above example, then ' x' would have either shown declaration error:
“x is undeclared".
a) Example that combines use of parameter self and multiple object declarations:
class Student:
roll = 0
name = ""
wt = 0.0
def accept(self):
print("Enter roll number")
self.roll = int(input( ))
print("Enter name")
self.name=input( )
print("Enter weight")
self.wt=float(input( ))
def display(self):
print("Roll number :",self.roll)
print("Name :",self.name)
print("Weight :",self.wt)
Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi
s1 = Student( ) # declaring object 's1' of class Student
s2 = Student( ) # declaring object 's2' of class Student
print("Accepting Details of first student")
s1.accept( ) # calling to member-function accept_details( ) for object 's1'
print("Accepting Details of second student")
s2.accept( ) # calling to member-function acceptdetails( ) for object 's2'
print("Showing Details of first student")
s1.display( ) # calling to member-function show_details( ) for object ‘s1’
print("Showing Details of second student")
s2.display( ) # calling to member-function show details( ) for object 's2'
Output
Accepting Details of first student
Enter roll number
10
Enter name
Akshay
Enter weight
80
Accepting Details of second student
Enter roll number
20
Enter name
Amol
Enter weight
75
Showing Details of first student
Roll number : 10
Name : Akshay
Weight : 80.0
Showing Details of second student
Roll number : 20
Name : Amol
Weight : 75.0
Note that, three attributes roll, name and wt needed to be initialized for their declaration to be happen.
Also note that, the member-functions are using parameter self to refer to attributes.
One more thing, we don't have to pass any actual parameter to member-functions for parameter self.
The parameter self will get initialized by invoking object itself.
class Student:
def accept(self,x,y,z): # Function with additional three parameters
self.roll = x
self.name = y
self.wt = z
def display(self):
print("Roll number :",self.roll)
print("Name :",self.name)
print("Weight :",self.wt)
s1 = Student( )
s2 = Student( )
print("Accepting Details of first student")
s1.accept(15, "Akshay" , 80)
print("Accepting Details of second student")
s2.accept(20,"Amol", 75 )
print("Showing Details of first student")
s1.display( )
print("Showing Details of second student")
s2.display( )
Output:
Accepting Details of first student
Accepting Details of second student
Showing Details of first student
Roll number : 15
Name : Akshay
Weight : 80
Showing Details of second student
Roll number : 20
Name : Amol
Weight : 75
This program is to clear that, we have not passed any parameter for ‘self’, but we needed to pass for
other three parameters.
In class student of Example b, we saw that the data members must be initialized to let their declaration
happen.
class Student:
roll = 0
name = ""
wt = 0.0
But it’s a tedious and code extending job. So we can also declare/add new data members from a
member function using ‘self’ as below.
class Student:
def accept(self):
print("Enter roll number")
self.roll = int(input( ))
print("Enter name")
self.name=input( )
print("Enter weight")
self.wt=float(input( ))
def display(self):
print("Roll number :",self.roll)
print("Name :",self.name)
print("Weight :",self.wt)
s1 = Student( )
s2 = Student( )
s1.accept( )
s2.accept( )
s1.display( )
s2.display( )
Here we can see that declaration of all three members i,e, roll, name and wt is done. Means whenever
function accept() is called for any object, the parameter self will automatically create and add three
data members for invoking object.
s1 and s2 are two objects of class student that add and initializes attributes name roll and wt to class
student. Similarly, we can add new attributes from any member-functions. The only condition is, these
attributes will be added only when that member-function is called (if not called, then these attributes
will not be added.)
Another way for externally adding attributes to an object is, by using directly object name with
attribute's initialization. Refer following code.
class Test:
def sayHello(self):
print("Hello all")
t1=Test()
t2=Test()
t1.x= 10 #externally added attribute in object t1
print(t1.x)
print(t2.x) # but not available for object t2 of same class
Note that, attribute `x' is externally added for object t1 and initialized with 10. But this type of external
insertion of attribute will be available only to that particular object. Therefore if we print the attribute
'x ' for object t2 (at Line-8) then it will show following error :
This clearly means that, if we declare attributes within class (internally), then those attributes are
available to every declared object of that class. But if we add attributes externally, then those attributes
are available to that particular object only.
Note that, in Line-11 we externally delete attribute 'x from class Test. Hence, above code will show
error AttributeError 'Test' object has no attribute "x' in Line-12 and Line-13.
class Student:
def __init__(self):
print("Constructor of class Student")
print("Declaring first object")
s1 = Student( ) # will create object sl and constructor executes here
print("Declaring second object")
s2 = Student( ) # will create object s2 and constructor executes here
Two objects s1 and s2 are declared for class Student and hence, constructor __int__ () function executes
individually for both object objects. Hence, note that output of above code.
Characteristics of constructor
Default constructor
Parameterized constructor
The default constructor is simple constructor which does not accept any arguments. Its definition has only one
argument which is a reference to the instance being constructed.
Example:
class Student :
def __init__(self): # this is default constructor to initialize default values to attributes
self.age = 18
self.gender = "Male"
self.dept = "CS"
def show_values(self):
print("Age :",self.age)
print("Gender :",self.gender)
print("Department :",self.dept)
Q] Define a class rectangle using length and width.It has a method which can compute area.
class rectangle:
def __init__(self,L,W):
self.L=L
self.W=W
def area(self):
return self.L*self.W
r=rectangle(2,10)
print(r.area())
Q] Create a circle class and initialize it with radius. Make two methods getarea and
getcircumference inside this class
class circle:
def __init__(self,radius):
self.radius=radius
def getarea(self):
return 3.14*self.radius*self.radius
def getcircumference(self):
return 2*3.14*self.radius
c=circle(5)
print("Area=",c.getarea())
print("Circumference=",c.getcircumference())
Other OOP languages allow Constructor Overloading and Function Overloading to improve readability
of code. Python does not allow Constructor Overloading and Function Overloading.
Example:
class Student :
def __init__(self): # this is default constructor to initialize default values to attributes
self.age = 18
self.gender = "Male"
self.dept = "CS"
def __init__(self,a,g,d): # defines parameterized constructor
self.age = a
self.gender = g
self.dept = d
def show_values(self):
print("Age :",self.age)
print(" Gender :",self.gender)
print("Department :",self.dept)
s1 = Student( ) # will create object s1 and invokes default constructor
s1 .show_values( )
s2 = Student( 18,"Female","CO") # will create object s2 and invokes parameterized constructor
s2.show_values( )
Above code will show error, Python strictly don't allow function overloading or constructor
overloading
It is because; in Python even a function is also treated as object. Hence, always last defined body of
overloaded constructor and function will be considered for use.
Hence, for above class Student, the last defined constructor (parameterized with 'a','g' and ‘d’ ) will get
considered to use.
Hence, it will show error if we use first constructor (default constructor).
But if we comment lines s1 = Student( ) and s1 .show_values( ) , then it will invoke parameterized
construction which will give correct output.
- As the Python don't allow constructor overloading and function overloading. But by assigning default
values to constructor's parameters we can achieve similar benefits as we can do by overloading. Here
is an example of combining application of initialization through default constructor and parameterized
constructor.
class Student :
def __init__(self,a=18,g="Male",d="CO"): # defines parameterized constructor with default values
self.age = a
self.gender = g
self.dept = d
def show_values(self):
print("Age :",self.age)
print(" Gender :",self.gender)
print("Department :",self.dept)
s1 = Student( ) # will create object s1 and invokes constructor with default values
print("Initialized Values of First Object")
s1 .show_values( )
s2 = Student( 20,"Female","IT") # will create object s2 and invokes parameterized constructor with
default values
print("Initialized Values of Second Object")
s2.show_values( )
Output:
Initialized Values of First Object
Age : 18
Gender : Male
Department : CO
Initialized Values of Second Object
Age : 20
Gender : Female
Department : IT
Note that, the parameterized constructor with default values will make it optional to pass arguments
for object s1.
And when arguments are passed for object s2, it will get updated.
A class can define a special method called destructor with the help of _ _del_ _().
It is invoked automatically when the scope of an object expires or the instance (object) is about to
be destroyed.
It is mostly used to clean up non memory resources used by an instance(object).
Example :
class Test:
def __init__(self):
print("Constructor is Invoked")
def __del__(self):
print("Destructor is Invoked")
s1=Test( )
del s1
s2 = Test()
del s2
Output:
Constructor is Invoked
Destructor is Invoked
Constructor is Invoked
Destructor is Invoked
class Test:
def __init__(self):
print("This is constructor")
def __del__(self):
print("This is destructor")
print("Declaring object t1")
t1=Test( ) #will create object t1 and invokes constructor automatically
t1.__init__() #calling constructor manually
t1.__del__() # calling destructor manually
print("Last Line") #scope of t1 expires and invokes destructor automatically
Output:
Declaring object t1
This is constructor
This is constructor
This is destructor
Last Line
Here,
Line- 7 declares object t1 and hence, constructor executes for object t1, automatically (according to its
characteristics).
Line-8 manually calls to constructor for object
Line-9 manually calls to destructor for object
Line-10 is last line of main script and after executing print statement, scope of t1 expires. Hence,
destructor executes automatically.
- It is possible that while working on an object, we need to reset the initial values of an object that we
initialized through default constructor; in other languages we cannot do it hence we are forced to
declare and use a new object, But Python allows to call constructor manually. Hence, if required to
reset then we manually call to constructor and reset the initialized values for an object.
- Same thing for destructor! Generally we define destructor to release the resources occupied by an
object. It is possible that we want to release the resources of occupied by an object even earlier to
expiration of its scope and earlier to its automatic execution. So we should call a destructor manually.
Although for any object, its constructor and destructor is called then also its constructor and destructor
will definitely execute on its automatic moments also.
Python allows to manually delete entire object by using keyword 'del ' followed by the object to be
deleted. For example,
class Student:
………..
……..
s1 = Student( )
s2 = Student( )
-Once an object is manually deleted, that object or its instances will no more be available to use. Refer
following code and error.
class Student:
x1=10
s1=Student()
print(“s1.x=”, s1.x)
del s1 # deletes object ‘s1'
print(“s1.x=”, s1.x) # will show NameError
b.method1()
b.method2()
b.method1()
b.method2()
class Test:
__a =15 # declares private variable
_b =20 # declares protected variable
t1=Test()
print("Private Variable=", t1.__a)
print("Protected Variable=", t1._b)
Here
line 1 declares private variable
line 2 declares protected variable
line 5 prints value of private variable outside class(will show error)
line 6 prints value of protected variable outside class
In the above program, we tried to access private attribute outside the class using object and it threw7a-
an exception,
Traceback (most recent call last):
File "C:/Python/Python38/PRACTICALS/Chapter 5/13_Data Hiding.py", line 5, in <module>
print("Private Variable=", t1.__a)
AttributeError: 'Test' object has no attribute '__a'
We can access the value of hidden attribute by a tricky syntax as
object._className__attrNmae
class Test:
__a =15 # declares private variable
_b =20 # declares protected variable
t1=Test()
print("Private Variable=", t1._Test__a)
print("Protected Variable=", t1._b)
Output:
Private Variable= 15
Protected Variable= 20
- From above output, note that the protected variable will be available outside the class for sure.
- However, these concepts of Data-Hiding are valid only while accessing members outside the class. But
there is no effect of Data-Hiding within the class. Here is another program, which increments values of
private and protected attributes within the class.
class Test:
__a = 10
_b =20
def increment(self):
print("Initial values")
print("Private variable =", self.__a )
print("Protected variable = ",self._b)
print(" \nAfter incrementing")
self.__a+=1
self._b+=1
print("Private variable =", self.__a)
print("Protected variable = ",self._b)
t1=Test()
t1.increment()
Output:
Initial values
Private variable = 10
Protected variable = 20
After incrementing
Private variable = 11
Protected variable = 21
- The class whose properties are being derived is called as base class or parent class or super class.
And the class which derives properties of base class is called as derived class or child class or sub class.
Benefits of Inheritance:
class BaseClass:
………….
………….
class DerivedClass(BaseClass):
……….
………
The base class name is provided inside parenthesis followed by derived class name. Python supports
five types of inheritance
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Let us discuss these all and other additional required concepts in inheritance.
Example 1:
class Student:
def accept(self):
print("Enter Name and Roll")
self.name=input()
self.roll=int(input())
def display(self):
print("Name is", self.name)
print("Roll is", self.roll)
class Marks(Student):
def accept_marks(self):
print("Enter Marks")
self.m=int(input())
def display_marks(self):
print("Marks are",self.m)
m1=Marks()
m1.accept()
m1.accept_marks()
m1.display()
m1.display_marks()
Output:
class Student:
def accept(self):
self.name='Amol'
self.roll= 15
def display(self):
print("Name is", self.name)
print("Roll is", self.roll)
class Marks(Student):
def accept_marks(self):
self.m1=50
self.m2=65
def display_marks(self):
print("Marks of Subject 1 are",self.m1)
print("Marks of Subject 2 are",self.m2)
M=Marks()
M.accept()
M.accept_marks()
M.display()
M.display_marks()
Output:
Name is Amol
Roll is 15
Marks of Subject 1 are 50
Marks of Subject 2 are 65
class Student:
def __init__(self):
print("Constructor of Base class")
def __del__(self):
print("Destructor of Base class")
class Marks(Student):
def __init__(self):
print("Constructor of Derived class")
def __del__(self):
print("Destructor of Derived class")
M=Marks()
del M
print("Main Area Ends")
In above example we have created constructor __init__() and destructor __del__ in both base and
derived classes.
Python interpreter will treat this as method overriding (because of same names in base and derived
class).
Hence constructor and destructor of derived class only executed.
Output:
Constructor of Derived class
Destructor of Derived class
Main Area Ends
If we want to call Base Class Constructor and Destructor from Derived class by using:
base_class_name.__init__(self)
and
base_class_name.__del__(self)
Example
class Student:
def __init__(self):
print("Constructor of Base class")
def __del__(self):
print("Destructor of Base class")
class Marks(Student):
def __init__(self):
Student.__init__(self)
print("Constructor of Derived class")
def __del__(self):
Student.__del__(self)
print("Destructor of Derived class")
M=Marks()
del M
print("Main Area Ends")
Output:
Constructor of Base class
Constructor of Derived class
Destructor of Base class
Destructor of Derived class
Main Area Ends
class Student:
def __init__(self, name, roll):
self.name= name
self.roll= roll
def display(self):
print("Name is", self.name)
print("Roll is", self.roll)
class Marks(Student):
def __init__(self,name,roll,m1,m2):
Student.__init__(self, name, roll)
self.m1=m1
self.m2=m2
def display_marks(self):
print("Marks of Subject 1 are",self.m1)
print("Marks of Subject 2 are",self.m2)
M=Marks("akshay",25,57,65)
M.display()
M.display_marks()
Output:
Name is akshay
Roll is 25
Marks of Subject 1 are 57
Marks of Subject 2 are 65
In above example, name and roll is passed as argument to constructor in Base class Student from
constructor in Derived class Marks.
Syntax:
Class Base1:
Body of the class
Class Base2:
Body of the class
Class Derived(Base1, Base2):
Body of the class
Example
class A:
attr1=10
def method1(self):
print("Hello Method of Class A")
class B:
attr2=20
def method2(self):
print("Hello Method of Class B")
class C(A, B):
attr3=30
def method3(self):
print("Hello Method of Class C")
obj = C()
obj.method1()
obj.method2()
obj.method3()
print(obj.attr1)
print(obj.attr2)
print(obj.attr3)
Output:-
Hello Method of Class A
Hello Method of Class B
Hello Method of Class C
10
20
30
Output:-
Value of a in Class A is 10
Value of b in Class B is 20
Value of c in Class C is 30
class Student:
def __init__(self, name, roll):
self.name= name
self.roll= roll
def display(self):
print("Name is", self.name)
print("Roll is", self.roll)
class Marks:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def display_marks(self):
print("Marks of Subject 1 are",self.m1)
print("Marks of Subject 2 are",self.m2)
class Result(Student, Marks):
def __init__(self,name, roll, m1, m2, m3):
Student.__init__(self,name,roll)
Marks.__init__(self,m1,m2)
self.m3=m3
def calculate(self):
print("Extra Marks are",self.m3)
self.total=self.m1+self.m2+self.m3
print("Total Marks are",self.total)
R=Result("Akshay",23,56,67,20)
R.display()
R.display_marks()
R.calculate()
Output
Name is Akshay
Roll is 23
Marks of Subject 1 are 56
Marks of Subject 2 are 67
Extra Marks are 20
Total Marks are 143
Output:-
Hello Method of Class A
Hello Method of Class B
Hello Method of Class C
10
20
30
Here we just need to inherit the ABC class from the abc module in Python.
To define an abstract method we use the @abstractmethod decorator of the abc module.
It tells Python that the declared method is abstract and should be overridden in the child classes.
Syntax to create an abstract method in Python:
from abc import ABC, abstractmethod
class <Abstract_Class_Name>(ABC):
@abstractmethod
def <abstract_method_name>(self,other_parameters):
pass
We just need to put this decorator over any function we want to make abstract, and the abc module
takes care of the rest.
Example 1:
from abc import ABC, abstractmethod
class Polygon(ABC):
def display(self):
print("Display is Concrete Method")
@abstractmethod
def noofsides(self): # abstract method
pass
class Triangle(Polygon):
def noofsides(self): # overriding abstract method
print("Triangle has 3 sides")
class Quadrilateral(Polygon):
def noofsides(self): # overriding abstract method
print("Quadrilateral has 4 sides")
class Pentagon(Polygon):
def noofsides(self): # overriding abstract method
print("Pentagon has 5 sides")
class Hexagon(Polygon):
def noofsides(self): # overriding abstract method
print("Hexagon has 6 sides")
R = Triangle()
R.noofsides()
R.display()
K = Quadrilateral()
K.noofsides()
K.display()
P = Pentagon()
P.noofsides()
P.display()
H = Hexagon()
H.noofsides()
H.display()
Example 2:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def move(self):
pass
class Human(Animal):
def move(self):
print("I can walk and run")
class Snake(Animal):
def move(self):
print("I can crawl")
class Dog(Animal):
def move(self):
print("I can bark")
class Lion(Animal):
def move(self):
print("I can roar")
R = Human()
R.move()
K = Snake()
K.move()
R = Dog()
R.move()
K = Lion()
K.move()
Output:
I can walk and run
I can crawl
I can bark
I can roar
class Test:
def product(self,a, b): # First product method Takes two argument and print their product
self.p = self.a * self.b
print("Product of two numbers is ", self.p)
def product(self,a, b, c): # Second product method Takes three argument and print their product
self.a=a
self.b=b
self.c=c
self.p = self.a * self.b* self.c
print("Product is ", self.p)
t= Test()
t.product(4, 5) # This line shows an error
t.product(4, 5, 5) # This line will call the second product method
In the above code we have defined two product method, but we can only use the second product
method, as python does not supports method overloading. We may define many method of same name
and different argument but we can only use the latest defined method. Calling the other method will
produce an error. Like here calling product(4, 5) will produce an error as the latest defined product
method takes three arguments.
If we are in strictly need of such implementation, then we can use function with default arguments.
Example:
class Test:
def product(self,a=1,b=1,c=1):
self.a=a
self.b=b
self.c=c
self.p = self.a * self.b* self.c
print("Product is ", self.p)
t= Test()
print("Product of two numbers is")
t.product(4, 5)
print("Product of three numbers is")
t.product(4, 5, 5)
Output:
Product of two numbers is
Product is 20
Product of three numbers is
Product is 100s
class A:
def sayHello(self):
print("Hello from class A")
class B(A):
def sayHello(self):
print("Hello from class B")
b=B()
b.sayHello()
Output:
Hello from class B
In above example method sayHello() from class A will not be invoked as method sayHello() from class
B hides it.
super(derived_class_name,self).overridden_method_name()
Example:
class A:
def sayHello(self):
print("Hello from class A")
class B(A):
def sayHello(self):
super(B,self).sayHello()
print("Hello from class B")
b=B()
b.sayHello()
Arrow Computer Academy Unit 5 Prof. Akshay A. Somwanshi
Output:
Hello from class A
Hello from class B
class A:
def sayHello(self):
print("Hello from class A")
class B(A):
def sayHello(self):
A.sayHello(self) # calling method in Base class from method in derived class
print("Hello from class B")
b=B()
b.sayHello()
Output:
Hello from class A
Hello from class B
The python __str__ method returns the object representation in a string format. This method is
supposed to return a human-readable format which is used to display some information about the
object. This method is called when an object is printed or manually _ _str_ _ ( ) function is called for an
object.
The programmer has to define (actually override) this function and this method must return the String,
If we don't implement _ _str_ _( ) function in a class, then built-in object implementation is used that
actually calls _ _repr _ _ () function.
Example.
class A:
pass
class B:
def __str__(self):
return "Hello from object of class B"
a1=A()
b1=B()
print(a1) #__str__() is not defined for object a1 so repr is called
print(b1) #__str__( ) is defined for object bl
#print(b1.__str__())
Note the class A does not defines __str__( ) function but class B does. We will get following output for
this.
Output:
<__main__.A object at 0x000002AB419FCDF0>
Hello from object of class B
You may get some other hashcode for object a1 in your system, but object b1 is definitely executing _
__str__() function defined in class B.
2. _ _repr_ _()
The function is used as a fallback/backup that executes for an object on the same moments but only
when _ _str _ _( ) function is not defined for that object. But remember that, There is no fallback if
__repr__ ( ) function implementation is missing.
- Now the major difference between these two functions is, the _ _str_ _() function must return string
only whereas the _ _repr _ _() function can return any informatics objet such as Tuple or Dictionary or
List or anything. Here is an example.
class A:
pass
class B:
def __repr__(self):
return {1:"one", 2:"two"}
a1=A()
b1=B()
print("When object a1 gets ptinted : ",a1) #__str__() is not defined for object a1
print("When object b1 gets Printed :",b1.__repr__()) #__str__( ) is defined for object bl
Output:
When object a1 gets ptinted : <__main__.A object at 0x000001B6AC8ABDF0>
When object b1 gets Printed : {1: 'one', 2: 'two'}
Installation of NumPy
If you have Python and PIP already installed on a system, then installation of NumPy is very easy.
Goto path:-
C:\Users\Admin\AppData\Local\Programs\Python\Python311\Scripts
Press cmd
Enter pip install numpy
Once NumPy is installed, import it in your applications by adding the import keyword:
import numpy
Now NumPy is imported and ready to use.
NumPy is usually imported under the np alias.
import numpy as np
Now the NumPy package can be referred to as np instead of numpy.
Example
Use a tuple to create a NumPy array:
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
Output:-
[1 2 3 4 5]
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
Example
Create a 0-D array with value 42
import numpy as np
arr = np.array(42)
print(arr)
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
Example
Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
Example
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
Advantages
Fast and efficient for manipulating and analyzing data.
Data from different file objects can be loaded.
Easy handling of missing data
Size mutability: columns can be inserted and deleted from DataFrame and higher dimensional
objects
Data set merging and joining.
Flexible reshaping and pivoting of data sets
Powerful group by functionality for performing split-combine operations on data sets.
The first step of working in pandas is to ensure whether it is installed in the Python folder or not. If
not then we need to install it in our system using pip command.
import pandas as pd
Here, pd is referred to as an alias to the Pandas.
Series:
Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer,
string, float, python objects, etc.). Pandas Series is nothing but a column in a table.
Creating a Series
import pandas as pd
import numpy as np
# simple array
data = np.array(['A', 'r', 'r', 'o', 'w'])
ser = pd.Series(data)
print(ser)
Labels
If nothing else is specified, the values are labeled with their index number. First value has index 0, second
value has index 1 etc.
This label can be used to access a specified value.
Example
Return the first value of the Series:
print(ser[0])
Create Labels
With the index argument, you can name your own labels.
Example
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a, index = ["x", "y", "z"])
print(myvar)
import pandas as pd
data =
{
"Experience": [20, 10, 5],
"Salary": [50000, 40000, 15000]
}
#load data into a DataFrame object:
df = pd.DataFrame(data)
print(df)
Locate Row
As you can see from the result above, the DataFrame is like a table with rows and columns.
Pandas use the loc attribute to return one or more specified row(s)