KEMBAR78
0 - Unit-V OOP - Python Libraries | PDF | Class (Computer Programming) | Inheritance (Object Oriented Programming)
0% found this document useful (0 votes)
11 views92 pages

0 - Unit-V OOP - Python Libraries

This document provides an overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, inheritance, polymorphism, and data abstraction. It explains how to create classes and objects, utilize class and instance variables, and implement methods, along with examples of inheritance types and polymorphic behavior. Additionally, it covers the use of abstract classes and methods to achieve data abstraction in Python.

Uploaded by

Shreya Sinkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views92 pages

0 - Unit-V OOP - Python Libraries

This document provides an overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, inheritance, polymorphism, and data abstraction. It explains how to create classes and objects, utilize class and instance variables, and implement methods, along with examples of inheritance types and polymorphic behavior. Additionally, it covers the use of abstract classes and methods to achieve data abstraction in Python.

Uploaded by

Shreya Sinkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

UNIT-V: INTRODUCTION TO OBJECT ORIENTED

PROGRAMMING AND PYTHON LIBRARIES


PYTHON CLASSES AND OBJECTS
A class in Python is a user-defined template for creating objects. It bundles data
and functions together, making it easier to manage and use them. When we
create a new class, we define a new type of object. We can then create
multiple instances of this object type.
Classes are created using class keyword. Attributes are variables defined
inside the class and represent the properties of the class. Attributes can be
accessed using the dot . operator (e.g., MyClass.my_attribute).
Create a Class
# define a class
class Dog:
sound = "bark" # class attribute
Create Object
An Object is an instance of a Class. It represents a specific implementation of
the class and holds its own data.
Now, let’s create an object from Dog class.
class Dog:
sound = "bark"
# Create an object from the class
dog1 = Dog()
# Access the class attribute
print(dog1.sound)

sound attribute is a class attribute. It is shared across all instances of Dog class,
so can be directly accessed through instance dog1.
CLASS CONSTRUCTOR USING _ _INIT_ _() FUNCTION
In Python, class has __init__() function. It automatically initializes object attributes when
an object is created.
class Dog:
species = "Canine" # Class attribute

def _ _init_ _(self, name, age):


self.name = name # Instance attribute
self.age = age # Instance attribute

class Dog: Defines a class named Dog.


species: A class attribute shared by all instances of the class.
__init__ method: Initializes the name and age attributes when a new object is created.
INITIATE OBJECT WITH _ _INIT_ _
class Dog:
species = "Canine" # Class attribute

def __init__(self, name, age):


self.name = name # Instance attribute
self.age = age # Instance attribute

# Creating an object of the Dog class


dog1 = Dog("Buddy", 3)

print(dog1.name) # Output: Buddy


print(dog1.species) # Output: Canine
SELF PARAMETER
self parameter is a reference to the current instance of the class. It allows us to access
the attributes and methods of the object.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
print(f"{self.name} is barking!")

# Creating an instance of Dog # Output


dog1 = Dog("Buddy", 3)
dog1.bark() Buddy is Barking
_ _STR_ _ METHOD
__str__ method in Python allows us to define a custom string representation of an object. By default, when we
print an object or convert it to a string using str(), Python uses the default implementation.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
return f"{self.name} is {self.age} years old." # Correct: Returning a string

dog1 = Dog("Buddy", 3)
dog2 = Dog("Charlie", 5)
#output
print(dog1) Buddy is 3 years old.
print(dog2) Charlie is 5 years old.
CLASS METHODS
Methods are the functions we use to describe the behavior of objects. They are
also defined inside a class.
class Car:
car_type = "Sedan"
def __init__(self, name, mileage):
self.name = name
self.mileage = mileage
def description(self):
return f“The {self.name} car gives the mileage of {self.mileage}km/l“
def max_speed(self, speed):
return f"The {self.name} runs at the maximum speed of {speed}km/hr"
obj2 = Car("Honda City",24.1)
print(obj2.description())
print(obj2.max_speed(150))

We know the methods defined inside a class, other than the constructor method, as instance methods.
Furthermore, we have two instance methods here – description() and max_speed().

description()- This method returns a string with the description of the car, such as the name and its
mileage. This method has no additional parameter. This method uses instance attributes.
max_speed()- This method has one additional parameter and returns a string displaying the car’s
name and speed
Note: Three important things to remember are-
You can create any number of objects in a class.
If the method requires n parameters and you do not pass the same number of arguments, then an
error will occur.
The order of the arguments matters.
MESSAGE PASSING
Message passing is how objects talk to each other in object-oriented programming. One object sends a message (calls a method) to another object to
make it do something or to get some information.
class Car:
def __init__(self, brand):
self.brand = brand
def start_engine(self):
print(f"The {self.brand} engine has started.")

class Driver:
def __init__(self, name):
self.name = name

def drive(self, car): #output


print(f"{self.name} is driving the car.") John is driving the car.
car.start_engine() The Toyota engine has started.
car = Car("Toyota") # In this example, the Driver object sends a message to the Car object by
driver = Driver("John") calling its start engine method through the drive method. This shows how

driver.drive(car) objects interact by sending messages to each other.


CLASS AND INSTANCE VARIABLES IN PYTHON
Class Variables
These are the variables that are shared across all instances of a class. It is defined at the class
level, outside any methods. All objects of the class share the same value for a class variable
unless explicitly overridden in an object.

Instance Variables
Variables that are unique to each instance (object) of a class. These are defined within __init__
method or other instance methods. Each object maintains its own copy of instance variables,
independent of other objects.
class Dog: # Access Class and Instance Variables
# Class variable print(dog1.species) #(class variable)
species = "Canine“ print(dog1.name) #(instance variable)
print(dog1.age) # (instance variable)
def __init__(self, name, age): # Modify instance variables
# Instance variables dog1.name = “Max”
self.name = name print(dog1.name) #(updated instance V)
self.age = age # Modify Class Variable
Dog.species = “Feline”
# Create objects print(dog1.species) #(updated class variable)
dog1 = Dog("Buddy", 3) print(dog2.species)
dog2 = Dog("Charlie", 5)
Ouput
Canine
Buddy
Charlie
Max
Feline
Feline
Class Variable (species): Shared by all instances of the class. Changing Dog.species affects all objects,
as it’s a property of the class itself.
Instance Variables (name, age): Defined in the __init__ method. Unique to each instance (e.g.,
dog1.name and dog2.name are different).
Accessing Variables: Class variables can be accessed via the class name (Dog.species) or an object
(dog1.species). Instance variables are accessed via the object (dog1.name).
Updating Variables: Changing Dog.species affects all instances. Changing dog1.name only affects
dog1 and does not impact dog2.
INHERITANCE IN PYTHON
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a
class (called a child or derived class) to inherit attributes and methods from another class
(called a parent or base class). This promotes code reuse, modularity, and a hierarchical class
structure.
Inheritance allows us to define a class that inherits all the methods and properties from
another class.
Syntax for Inheritance
class ParentClass:
# Parent class code here
pass
class ChildClass(ParentClass):
# Child class code here
pass
Parent Class:
This is the base class from which other classes inherit.
It contains attributes and methods that the child class can reuse.

Child Class:
This is the derived class that inherits from the parent class.
The syntax for inheritance is class ChildClass (ParentClass).
The child class automatically gets all attributes and methods of the
parent class unless overridden.
# Parent class
class Animal:
def __init__(self, name):
self.name = name # Initialize the name attribute

def speak(self):
pass # Placeholder method to be overridden by child classes

# Child class inheriting from Animal


class Dog(Animal):
def speak(self):
return f"{self.name} barks!" # Override the speak method

# Creating an instance of Dog #output


dog = Dog("Buddy") Buddy barks!
print(dog.speak())
CREATING A PARENT CLASS
In object-oriented programming, a parent class (also known as a base class) defines common
attributes and methods that can be inherited by other classes. These attributes and methods
serve as the foundation for the child classes. By using inheritance, child classes can access and
extend the functionality provided by the parent class.
# A Python program to demonstrate inheritance
class Person(object):

# Constructor
def __init__(self, name, id):
self.name = name
self.id = id

# To check if this person is an employee


def Display(self):
print(self.name, self.id)
# Driver code #output
emp = Person("Satyam", 102) # An Object of Person Satyam 102
emp.Display()
CREATING A CHILD CLASS
A child class (also known as a subclass) is a class that inherits properties and
methods from its parent class. The child class can also introduce additional
attributes and methods, or even override the ones inherited from the parent.
In this case, Emp is the child class that inherits from the Person class:
class Emp(Person):
def Print(self):
print("Emp class called")
Emp_details = Emp("Mayank", 103)
# calling parent class function
Emp_details.Display()
# Calling child class function
Emp_details.Print()
TYPES OF PYTHON INHERITANCE
1) Single Inheritance: A child class inherits from one parent class.
2) Multiple Inheritance: A child class inherits from more than one parent class.
3) Multilevel Inheritance: A class is derived from a class which is also derived from another class.
4) Hierarchical Inheritance: Multiple classes inherit from a single parent class.
5) Hybrid Inheritance: A combination of more than one type of inheritance.

# 1. Single Inheritance
class Person:
def __init__(self, name):
self.name = name
class Employee(Person): # Employee inherits from Person
def __init__(self, name, salary):
super().__init__(name)
self.salary = salary
# 2. Multiple Inheritance
class Job:
def __init__(self, salary):
self.salary = salary
class EmployeePersonJob(Employee, Job): # Inherits from both Employee and Job
def __init__(self, name, salary):
Employee.__init__(self, name, salary) # Initialize Employee
Job.__init__(self, salary) # Initialize Job
# 3. Multilevel Inheritance
class Manager(EmployeePersonJob): # Inherits from EmployeePersonJob
def __init__(self, name, salary, department):
EmployeePersonJob.__init__(self, name, salary) # Explicitly initialize EmployeePersonJob
self.department = department
# 4. Hierarchical Inheritance
class AssistantManager(EmployeePersonJob): # Inherits from EmployeePersonJob
def __init__(self, name, salary, team_size):
EmployeePersonJob.__init__(self, name, salary) # Explicitly initialize EmployeePersonJob
self.team_size = team_size

# 5. Hybrid Inheritance (Multiple + Multilevel)


class SeniorManager(Manager, AssistantManager): # Inherits from both Manager and
AssistantManager
def __init__(self, name, salary, department, team_size):
Manager.__init__(self, name, salary, department) # Initialize Manager
AssistantManager.__init__(self, name, salary, team_size) # Initialize AssistantManager
# Creating objects to show inheritance
# Single Inheritance
emp = Employee("John", 40000)
print(emp.name, emp.salary)
# Multiple Inheritance
emp2 = EmployeePersonJob("Alice", 50000)
print(emp2.name, emp2.salary)
# Multilevel Inheritance
mgr = Manager("Bob", 60000, "HR")
print(mgr.name, mgr.salary, mgr.department)
# Hierarchical Inheritance
asst_mgr = AssistantManager("Charlie", 45000, 10)
print(asst_mgr.name, asst_mgr.salary, asst_mgr.team_size) # Hybrid Inheritance
sen_mgr = SeniorManager("David", 70000, "Finance", 20)
print(sen_mgr.name, sen_mgr.salary, sen_mgr.department, sen_mgr.team_size)
POLYMORPHISM IN PYTHON
Polymorphism is a foundational concept in programming that allows entities like functions, methods or
operators to behave differently based on the type of data they are handling. Derived from Greek,
the term literally means “many forms”.
Python’s dynamic typing and duck typing make it inherently polymorphic. Functions, operators and
even built-in objects like loops exhibit polymorphic behavior.
print(len("Hello")) # String length
print(len([1, 2, 3])) # List length
print(max(1, 3, 2)) # Maximum of integers
print(max("a", "z", "m")) # Maximum in strings
In OOP, polymorphism allows methods in different classes to share the same name but perform
distinct tasks. This is achieved through inheritance and interface design. Polymorphism complements
other OOP principles like inheritance (sharing behavior) and encapsulation (hiding complexity) to
create robust and modular applications.
class Shape:
def area(self):
return "Undefined"
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
shapes = [Rectangle(2, 3), Circle(5)]
for shape in shapes:
print(f"Area: {shape.area()}")
class Animal:
def sound(self):
return "Some generic sound"

class Dog(Animal): #output


def sound(self): hi
return “hi“ hello
Some generic sound
class Cat(Animal):
def sound(self):
return “hello"

# Polymorphic behavior
animals = [Dog(), Cat(), Animal()]
for animal in animals:
print(animal.sound()) # Calls the overridden method based on the object type
DATA ABSTRACTION IN PYTHON
Data abstraction is one of the most essential concepts of Python OOPs which is used to hide irrelevant
details from the user and show the details that are relevant to the users.

A simple example of this can be a car. A car has an accelerator, clutch, and break and we all know
that pressing an accelerator will increase the speed of the car and applying the brake can stop the
car but we don't know the internal mechanism of the car and how these functionalities can work this
detail hiding is known as data abstraction.

Data abstraction in Python is a programming concept that hides complex implementation details while
exposing only essential information and functionalities to users. In Python, we can achieve data
abstraction by using abstract classes and abstract classes can be created using abc (abstract base
class) module and abstractmethod of abc module.
ABSTRACTION CLASSES IN PYTHON
Abstract class is a class in which one or more abstract methods are defined. When a method is
declared inside the class without its implementation is known as abstract method.
Abstract Method: In Python, abstract method feature is not a default feature. To create abstract
method and abstract classes we have to import the "ABC" and "abstractmethod" classes from abc
(Abstract Base Class) library. Abstract method of base class force its child class to write the
implementation of the all abstract methods defined in base class. If we do not implement the abstract
methods of base class in the child class then our code will give error. In the below code method_1 is a
abstract method created using @abstractmethod decorator.
from abc import ABC, abstractmethod
class BaseClass(ABC):
@abstractmethod
def method_1(self):
#empty body
pass
Concrete Method: Concrete methods are the methods defined in an abstract base class with their
complete implementation. Concrete methods are required to avoid replication of code in subclasses.
For example, in abstract base class there may be a method that implementation is to be same in all its
subclasses, so we write the implementation of that method in abstract base class after which we do not
need to write implementation of the concrete method again and again in every subclass. In the below
code startEngine is a concrete method.

class Car(ABC):
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
self.engine_started = True
def startEngine(self):
if not self.engine_started:
print(f"Starting the {self.model}'s engine.")
self.engine_started = True
else:
print("Engine is already running.")
IMPLEMENTATION OF DATA ABSTRACTION IN PYTHON
In the below code, we have implemented data abstraction using abstract class and method. Firstly, we
import the required modules or classes from abc library then we create a base class 'Car' that
inherited from 'ABC' class that we have imported. Inside base class we create init function, abstract
function and non-abstract functions. To declare abstract function printDetails we use
"@abstractmethod" decorator. After that we create child class hatchback and suv. Since, these child
classes inherited from abstract class so, we need to write the implementation of all abstract function
declared in the base class. We write the implementation of abstract method in both child class. We
create an instance of a child class and call the printDetails method. In this way we can achieve the
data abstraction.
# Import required modules # create a child class
from abc import ABC, abstractmethod class Hatchback(car):
# Create Abstract base class def PrintDetails(self):
class Car(ABC): Print(“Brand”,self.brand)
def __init__(self, brand, model, year): Print(“Model”,self.model)
self.brand = brand Print(“Year”, self.year)
self.model = model def sunroof(self):
self.year = year print(“Not having this feature”)
# Create abstract method # create a child class
@abstractmethod Class Suv(Car):
def printDetails(self): def PrintDetails(self):
pass Print(“Brand”, self.brand)
# Create concrete method Print(“Model”,self.model)
def accelerate(self): Print(“Year”, self.year)
print("Speed up ...") def sunroof(self):
def break_applied(self): print(“available”)
print("Car stopped")
# Create an instance of the Hatchback class
car1 = Hatchback("Maruti", "Alto", "2022")
# Call methods
car1.printDetails()
car1.accelerate()
car1.sunroof()

Output
Brand: Maruti
Model: Alto
Year: 2022
Speed up ...
Not having this feature
ENCAPSULATION
Encapsulation is a way to ensure security. Basically, it hides the data from the access of
outsiders. Such as, if an organization wants to protect an object/information from unwanted
access by clients or any unauthorized person, then encapsulation is the way to ensure this.
You can declare methods or attributes as protected by using a single underscore (_) before their
names, like _self.name or def _method(). Both lines indicate that the attribute and method are
protected, accessible only within the class and subclasses, but can be accessed by class methods
and objects.
Though Python uses ‘ _ ‘ just as a coding convention, it tells that you should use these
attributes/methods within the scope of the class. But you can still access the variables and
methods which are defined as protected, as usual.
Though Python uses ‘ _ ‘ just as a coding convention, it tells that you should use these
attributes/methods within the scope of the class. But you can still access the variables and
methods which are defined as protected, as usual.
Now to actually prevent the access of attributes/methods from outside the scope of a class, you
can use “private members“. In order to declare the attributes/method as private members, use
double underscore ( ) in the prefix. Such as – self.name or def __method(); Both of these lines
tell that the attribute and method are private and access is not possible from outside the class.
class car:
def __init__(self, name, mileage):
self._name = name #protected variable
self.mileage = mileage
def description(self):
return f"The {self._name} car gives the mileage of {self.mileage}km/l“
obj = car("BMW 7-series",39.53)
#accessing protected variable via class method
print(obj.description())
#accessing protected variable directly from outside
print(obj._name)
print(obj.mileage)
Let us see how encapsulation works,
class Car:
def __init__(self, name, mileage):
self.__name = name #private variable
self.mileage = mileage
def description(self):
return f"The {self.__name} car gives the mileage of {self.mileage}km/l“

obj = Car("BMW 7-series",39.53)

#accessing private variable via class method


print(obj.description())
#accessing private variable directly from outside
print(obj.mileage)
print(obj._Car__name) #mangled name
REUSABILITY
Functions and Modules
Functions are blocks of reusable code that perform a specific task. For example:
def add(a, b):
return a + b
def multiply(a, b):
return a * b
# Reusing functions in another part of the application
result_add = add(10, 5)
result_multiply = multiply(10, 5)
Modules are files containing Python code that can be imported and reused. For instance
math_operations.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
main.py
import math_operations as mo
result_add = mo.add(5, 3)
result_multiply = mo.multiply(5, 3)
print(result_add) # Output: 8
print(result_multiply) # Output: 15
INSTANCE METHOD
. Using the instance method, we can access or modify the calling object’s attributes.
. Instance methods are defined inside a class, and it is pretty similar to defining a regular function.
. Use Def keyword to define instance Method.
. Use self as a first parameter in instance method when defining it. The self parameter refers to current object.
. Using the self parameter to access or modify current object attributes.
class Student:
# constructor
def __init__(self, name, age):
# Instance variable
self.name = name
self.age = age
# instance method to access instance variable
def show(self):
print('Name:', self.name, 'Age:', self.age)
CALLING AN INSTANCE METHOD
We use an object and dot (.) operator to execute the block of code or action defined in the instance
method.
. First, create instance variables name and age in student class.
. Create an instance method display() to print student name and age.
. Next, create object of student class to call instance method.
Lets see how to call an instance method show() to access student object details such as name and age.
class Student:
# constructor
def __init__(self, name, age):
# Instance variable
self.name = name
self.age = age
# instance method access instance variable
def show(self):
print('Name:', self.name, 'Age:', self.age)
# create first object
print('First Student')
emma = Student("Jessa", 14)
# call instance method
emma.show()

# output
First Student
Name : Jessa Age : 14
NumPy library in Python
NumPy stands for Numerical Python and is one of the most useful scientific libraries in
Python programming. It provides support for large multidimensional array objects and
various tools to work with them.
Arrays are a collection of elements/values, that can have one or more dimensions. An
array of one dimension is called a Vector while having two dimensions is called a
Matrix.
NumPy arrays are called ndarray or N-dimensional arrays and they store elements of
the same type and size. It is known for its high-performance and provides efficient
storage and data operations as arrays grow in size.
Creating a NumPy Array
●NumPy arrays are very easy to create given the complex problems they solve. To create a
very basic ndarray, you use the np.array() method. All you have to pass are the values of
the array as a list:
● This array contains integer values. You can specify the type of data in the dtype argument:
● np.array([1,2,3,4],dtype=np.float32)
● Output:
● array([1., 2., 3., 4.], dtype=float32)
Since NumPy arrays can contain only homogeneous datatypes, values will be upcast if the types do not

match:
np.array([1,2.0,3,4])

Output:

array([1., 2., 3., 4.])


Here, NumPy has upcast integer values to float values.


NumPy arrays can be multi-dimensional too


np.array([[1,2,3,4],[5,6,7,8]])

array([[1, 2, 3, 4],

[5, 6, 7, 8]])
Here, we created a 2-dimensional array of values.

Note: A matrix is just a rectangular array of numbers with shape N x M where N is the number of rows

and M is the number of columns in the matrix. The one you just saw above is a 2 x 4 matrix.
Size of NumPy array
●You can determine how many values there are in the array using the size attribute. It
just multiplies the number of rows by the number of columns in the ndarray:

● # size of array
● a = np.array([[5,10,15],[20,25,20]])
● print('Size of array :',a.size)
● print('Manual determination of size of array :',a.shape[0]*a.shape[1])

● Size of array : 6
● Manual determination of size of array : 6
Mathematical Operations in Numpy
Addition
The add() function sums the content of two arrays, and return the results in a new array.

import numpy as np

arr1 = np.array([10, 11, 12, 13, 14, 15])


arr2 = np.array([20, 21, 22, 23, 24, 25])

newarr = np.add(arr1, arr2)

print(newarr)

# output

[30,32,34,36,38]
Subtraction
The subtract() function subtracts the values from one array with the values from another array,
and return the results in a new array.

import numpy as np

arr1 = np.array([10, 20, 30, 40, 50, 60])


arr2 = np.array([20, 21, 22, 23, 24, 25])

newarr = np.subtract(arr1, arr2)

print(newarr)

# output

[-10, -1, 8 , 17, 26, 35]


numpy.square() in Python

This mathematical function helps user to calculate square value of each element in the array.

Parameters :
arr : [array_like] Input array or object whose elements, we need to square.

# Python program explaining


# square () function

import numpy as np

arr1 = [1, -3, 15, -466]


print ("Square Value of arr1 : \n", np.square(arr1))

arr2 = [23 ,-56]


print ("\nSquare Value of arr2 : ", np.square(arr2))

Square Value of arr1 : [ 1 9 225 217156] Square Value of arr2 : [ 529 3136]
Trignometric Functions in Numpy
NumPy provides the sin(), cos() and tan() that take values in radians and produce the corresponding sin,
cos and tan values.

import numpy as np

x = np.sin(np.pi/2)

print(x)

# output
1.0

Find sine values for all of the values in arr:

import numpy as np

arr = np.array([np.pi/2, np.pi/3, np.pi/4, np.pi/5])

x = np.sin(arr)

print(x) # output [1. 0.8660254 0.70710678 0.58778525]


Conditional operations in Numpy
Conditional operations on NumPy arrays allow for element-wise comparisons and selections based on
specified criteria. These operations are fundamental for data manipulation and analysis, enabling users
to filter, modify, or extract data that meet certain conditions.

Comparison Operators
Comparison operators such as < , > , <= , >=, = = , ! = can be applied directly to NumPy
arrays, resulting in a boolean array indicating the truth value of the condition for each
element.

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
mask = arr > 2
print(mask)

# Output: [False False True True True]


Boolean Indexing
Boolean arrays can be used to index NumPy arrays, selecting only the elements corresponding
to True values in the boolean array.

filtered_arr = arr[mask]print(filtered_arr)

# Output: [3 4 5]

np.where() :- The np.where() function provides a versatile way to perform conditional


operations. It returns elements chosen from two arrays based on a condition or the indices
where a condition is satisfied.

new_arr = np.where(arr > 2, arr * 2, arr / 2)


print(new_arr)
# Output: [0.5 1. 6. 8. 10.]
Combining Conditions
Multiple conditions can be combined using logical operators such
as & (and), | (or), and ~ (not).

combined_mask = (arr > 1) & (arr < 5)


print(arr[combined_mask])

# Output: [2 3 4]
Matrix Multiplication in NumPy

We will be using the numpy.dot() method to find the product of 2 matrices.

For example, for two matrices A and B.


A = [[1, 2], [2, 3]]
B = [[4, 5], [6, 7]]

So, A.B = [[1*4 + 2*6, 2*4 + 3*6], [1*5 + 2*7, 2*5 + 3*7]

So the computed answer will be: [[16, 26], [19, 31]]

In Python numpy.dot() method is used to calculate the dot product between two
arrays.
Example 1 : Matrix multiplication of 2 square matrices.
# importing the module
import numpy as np

# creating two matrices


p = [[1, 2], [2, 3]]
q = [[4, 5], [6, 7]] # output
print("Matrix p :")
print(p) Matrix p : [[1, 2], [2, 3]]
print("Matrix q :") Matrix q : [[4, 5], [6, 7]]
print(q)
The matrix multiplication is
# computing product : [[16 19] [26 31]]
result = np.dot(p, q)

# printing the result


print("The matrix multiplication is :")
print(result)
Example 2 : Matrix multiplication of 2 rectangular matrices.
# importing the module
import numpy as np

# creating two matrices


p = [[1, 2], [2, 3], [4, 5]] # output
q = [[4, 5, 1], [6, 7, 2]]
Matrix p : [[1, 2], [2, 3], [4, 5]]
print("Matrix p :")
Matrix q : [[4, 5, 1], [6, 7, 2]]
print(p)
print("Matrix q :") The matrix multiplication is :
print(q) [[16 19 5] [26 31 8] [46 55 14]]

# computing product
result = np.dot(p, q)

# printing the result


print("The matrix multiplication is :")
print(result)
Indexing, and slicing
import numpy as np

# create a 1D array
array1 = np.array([1, 3, 5, 7, 8, 9, 2, 4, 6])

# slice array1 from index 2 to index 6 (exclusive) # output


print(array1[2:6]) # [5 7 8 9] [5 7 8 9]
[1 5 8 2]
# slice array1 from index 0 to index 8 (exclusive) with a step [7 8 9 2 4 6]
size of 2
[1 3 5 7 8 9 2 4 6]
print(array1[0:8:2]) # [1 5 8 2]

# slice array1 from index 3 up to the last element


print(array1[3:]) # [7 8 9 2 4 6]

# items from start to end


print(array1[:]) # [1 3 5 7 8 9 2 4 6]
Shape Manipulation in NumPy
Shape of Arrays
Printing the shape of the multidimensional array. In this example, two NumPy arrays arr1 and arr2 are
created, representing a 2D array and a 3D array, respectively. The shape of each array is printed,
revealing their dimensions and sizes along each dimension.

import numpy as npy

# creating a 2-d array # OUTPUT


arr1 = npy.array([[1, 3, 5, 7], [2, 4, 6, 8]]) (2, 4)
(2, 2,2)
# creating a 3-d array
arr2 = npy.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print(arr1.shape)
print(arr2.shape)
Shape of Array of Tuples

we’ll create a NumPy array where each element is a tuple. We’ll also demonstrate
how to determine the shape of such an array.
import numpy as np

# Create an array of tuples


array_of_tuples = np.array([(1, 2), (3, 4), (5, 6), (7, 8)])

# Display the array # OUTPUT


print("Array of Tuples:") Array of Tuples:
print(array_of_tuples) [[1 2]
[3 4]
[5 6]
[7 8]]
# Determine and display the shape
Shape of Array: (4, 2)
shape = array_of_tuples.shape
print("\nShape of Array:", shape)
Data Structures in Pandas
Pandas is an open-source library that uses for working with relational or labeled data both
easily and intuitively. It provides various data structures and operations for manipulating
numerical data and time series. It offers a tool for cleaning and processes your data. It is the
most popular Python library that is used for data analysis. In this article, We are going to learn
about Pandas Data structure.
It supports two data structures:
•Series
•Dataframe
Series
Pandas is a one-dimensional labeled array and capable of holding data of any type (integer, string, float, python
objects, etc.)

Syntax: pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)

Parameters:
•data: array- Contains data stored in Series.
•index: array-like or Index (1d)
•dtype: str, numpy.dtype, or ExtensionDtype, optional
•name: str, optional
•copy: bool, default False
Example 1: Series holding the char data type.

import pandas as pd
# a simple char list
list = ['g', 'e', 'e', 'k', 's']

# create series form a char list


res = pd.Series(list)
print(res)

#output
0 g
1 e
2 e
3 k
4 S
Dtype : object
Example 2: Series holding the Int data type.

import pandas as pd

# a simple int list


list = [1,2,3,4,5]

# create series form a int list


res = pd.Series(list)
print(res)

#output
0 1
1 2
2 3
3 4
4 5
Dtype : int64
Example 3: Series holding the dictionary.

import pandas as pd

dic = { 'Id': 1013, 'Name': ‘Sachin',


'State': 'MH','Age': 24}

res = pd.Series(dic)
print(res)

#output
Id 1013
Name Sachin
State MH
Age 24
Dtype : object
Dataframe

Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data


structure with labeled axes (rows and columns). A Data frame is a two-dimensional data structure,
i.e., data is aligned in a tabular fashion in rows and columns like a spreadsheet or SQL table, or a
dict of Series objects. . Pandas DataFrame consists of three principal components, the data, rows,
and columns.

Creating a Pandas DataFrame

In the real world, a Pandas DataFrame will be created by loading the datasets from existing
storage, storage can be SQL Database, CSV file, and Excel file. Pandas DataFrame can be
created from the lists, dictionary, and from a list of dictionary etc. Dataframe can be created in
different ways here are some ways by which we create a dataframe:
Example 1: DataFrame can be created using a single list or a list of lists.

# import pandas as pd
import pandas as pd

# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']

# Calling DataFrame constructor on list


df = pd.DataFrame(lst)
display(df)
Example 2: Creating DataFrame from dict of ndarray/lists.

To create DataFrame from dict of narray/list, all the narray must be of same length. If index is passed then the
length index should be equal to the length of arrays. If no index is passed, then by default, index will be
range(n) where n is the array length.

# Python code demonstrate creating


# DataFrame from dict narray / lists
# By default addresses.

import pandas as pd

# initialise data of lists.


data = {'Name':['Tom', 'nick', 'krish', 'jack'],
'Age':[20, 21, 19, 18]}

# Create DataFrame
df = pd.DataFrame(data)

# Print the output.


display(df)
Dealing with a column and row in DataFrame

Selection of column: In Order to select a column in Pandas DataFrame, we can either access the columns by
calling them by their columns name.

# Import pandas package


import pandas as pd

# Define a dictionary containing employee data


data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Age':[27, 24, 22, 32],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
'Qualification':['Msc', 'MA', 'MCA', 'Phd']}

# Convert the dictionary into DataFrame


df = pd.DataFrame(data)

# select two columns


print(df[['Name', 'Qualification']])
How to Select Rows and Column from Pandas DataFrame?

Example 1: Selecting rows.

pandas.DataFrame.loc is a function used to select rows from Pandas DataFrame based on the condition
provided.

Syntax: df.loc[df[‘cname’] ‘condition’]

Parameters:
•df: represents data frame
•cname: represents column name
•condition: represents condition on which rows has to be
selected
# Importing pandas as pd
from pandas import DataFrame

# Creating a data frame


Data = {'Name': ['Mohe', 'Shyni', 'Parul', 'Sam'],
'ID': [12, 43, 54, 32],
'Place': ['Delhi', 'Kochi', 'Pune', 'Patna']
}

df = DataFrame(Data, columns = ['Name', 'ID', 'Place'])

# Print original data frame


print("Original data frame:\n")
display(df)

# Selecting the product of Electronic Type


select_prod = df.loc[df['Name'] == 'Mohe']

print("\n")

# Print selected rows based on the condition


print("Selecting rows:\n")
display (select_prod)
Example 2: Selecting column.

# Importing pandas as pd
from pandas import DataFrame

# Creating a data frame


Data = {'Name': ['Mohe', 'Shyni', 'Parul', 'Sam'],
'ID': [12, 43, 54, 32],
'Place': ['Delhi', 'Kochi', 'Pune', 'Patna']
}

df = DataFrame(Data, columns = ['Name', 'ID', 'Place'])

# Print original data frame


print("Original data frame:")
display(df)

print("Selected column: ")


display(df[['Name', 'ID']] )
Python Pandas - Panel

A panel is a 3D container of data. The term Panel data is derived from econometrics and is
partially responsible for the name pandas − pan(el)-da(ta)-s.

The names for the 3 axes are intended to give some semantic meaning to describing operations
involving panel data. They are −

•items: axis 0, each item corresponds to a DataFrame contained inside.


•major_axis: axis 1, it is the index (rows) of each of the DataFrames.
•minor_axis: axis 2, it is the columns of each of the DataFrames.

pandas.Panel()

A Panel can be created using the following constructor −

Pandas.Panel(data, items, major_axis, minor_axis, dtype, copy)


The parameters of the constructor are as follows −

Parameter Description
Data takes various forms like
ndarray, series, map, lists, dict,
data
constants and also another
DataFrame
items axis=0
major_axis axis=1
minor_axis axis=2
dtype Data type of each column
copy Copy data. Default, false
Create Panel

A Panel can be created using multiple ways like −


•From ndarrays
•From dict of DataFrames

From 3D ndarray
Its output is as follows −

# creating an empty panel


import pandas as pd <class 'pandas.core.panel.Panel'> Dimensions: 2 (items)
import numpy as np x 4 (major_axis) x 5 (minor_axis)
data = np.random.rand(2,4,5) Items axis: 0 to 1
p = pd.Panel(data) Major_axis axis: 0 to 3
print(p) Minor_axis axis: 0 to 4
From dict of DataFrame Objects

#creating an empty panel


import pandas as pd
import numpy as np
data = {'Item1' : pd.DataFrame(np.random.randn(4, 3)),
'Item2' : pd.DataFrame(np.random.randn(4, 2))}
p = pd.Panel(data)
print(p)

Its output is as follows −

Dimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis)


Items axis: Item1 to Item2
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 2
Create an Empty Panel

An empty panel can be created using the Panel constructor as follows −

#creating an empty panel


import pandas as pd
p = pd.Panel()
print(p)
Its output is as follows −

<class 'pandas.core.panel.Panel'>
Dimensions: 0 (items) x 0 (major_axis) x 0 (minor_axis)
Items axis: None
Major_axis axis: None
Minor_axis axis: None
Selecting the Data from Panel

Select the data from the panel using −


•Items
•Major_axis
•Minor_axis

Using Items
# creating an empty panel
import pandas as pd
import numpy as np
data = {'Item1' : pd.DataFrame(np.random.randn(4,3)),
'Item2' : pd.DataFrame(np.random.randn(4,2))}
p = pd.Panel(data)
print(p['Item1'])
# output
0 1 2
0 0.488824 -0.128637 0.930817
1 0.417497 0.896681 0.576657
2 -2.775266 0.571668 0.290082
3 -0.400538 -0.144234 1.110535
Using major_axis

Data can be accessed using the method panel.major_axis(index).

# creating an empty panel


import pandas as pd
import numpy as np data = {'Item1' : pd.DataFrame(np.random.randn(4, 3)),
'Item2' : pd.DataFrame(np.random.randn(4, 2))}
p = pd.Panel(data)
print(p.major_xs(1))

Its output is as follows −

Item1 Item2
0 0.417497 0.748412
1 0.896681 -0.557322
2 0.576657 NaN
Using minor_axis

Data can be accessed using the method panel.minor_axis(index).

# creating an empty panel


import pandas as pd
import numpy as np data = {'Item1' : pd.DataFrame(np.random.randn(4, 3)),
'Item2' : pd.DataFrame(np.random.randn(4, 2))}
p = pd.Panel(data)
print(p.minor_xs(1))

Its output is as follows −

Its output is as follows −

Item1 Item2
0 -0.128637 -1.047032
1 0.896681 -0.557322
2 0.571668 0.4319533
3 -0.144234 1.302466
What is Matplotlib?

Matplotlib is a low level graph plotting library in python that serves as a visualization
utility.
Matplotlib was created by John D. Hunter.
Matplotlib is open source and we can use it freely.
Matplotlib is mostly written in python, a few segments are written in C, Objective-C and
Javascript for Platform compatibility.

Matplotlib Pyplot

Pyplot

Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under
the plt alias:

import matplotlib.pyplot as plt


ExampleGet your own Python Server
Draw a line in a diagram from position (0,0) to position (6,250):

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([0, 6])


ypoints = np.array([0, 250])

plt.plot(xpoints, ypoints)
plt.show()
Matplotlib Plotting

Plotting x and y points

The plot() function is used to draw points (markers) in a diagram.

By default, the plot() function draws a line from point to point.

The function takes parameters for specifying points in the diagram.

Parameter 1 is an array containing the points on the x-axis.

Parameter 2 is an array containing the points on the y-axis.

If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8] and [3, 10] to the
plot function.
Example Draw a line in a diagram from position (1, 3) to
position (8, 10):

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints)
plt.show()
Matplotlib Line

Linestyle
You can use the keyword argument linestyle, or shorter ls, to change the style of the plotted line :

import matplotlib.pyplot as plt


import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, linestyle = 'dotted')


plt.show()
Line Color

You can use the keyword argument color or the shorter c to set the color of the line:

import matplotlib.pyplot as plt


import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, color = 'r')


plt.show()
Multiple Lines

You can plot as many lines as you like by simply adding more plt.plot() functions:

Example
Draw two lines by specifying a plt.plot() function for each line:

import matplotlib.pyplot as plt


import numpy as np

y1 = np.array([3, 8, 1, 10])
y2 = np.array([6, 2, 7, 11])

plt.plot(y1)
plt.plot(y2)

plt.show()
Creating Bars

With Pyplot, you can use the bar() function to draw bar graphs:

ExampleGet your own Python Server


Draw 4 bars:

import matplotlib.pyplot as plt


import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.bar(x,y)
plt.show()
Horizontal Bars

If you want the bars to be displayed horizontally instead of vertically, use the barh() function:

Example
Draw 4 horizontal bars:

import matplotlib.pyplot as plt


import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.barh(x, y)
plt.show()
Bar Color
The bar() and barh() take the keyword argument color to set the color of the bars:

Example
Draw 4 red bars:

import matplotlib.pyplot as plt


import numpy as np

x = np.array(["A", "B", "C", "D"])


y = np.array([3, 8, 1, 10])

plt.bar(x, y, color = "red")


plt.show()
Matplotlib Pie Charts

Creating Pie Charts


With Pyplot, you can use the pie() function to draw pie charts:

Example
A simple pie chart:

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])

plt.pie(y)
plt.show()
Labels
Add labels to the pie chart with the labels parameter.
The labels parameter must be an array with one label for each wedge:

Example
A simple pie chart:

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])


mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels)


plt.show()
Start Angle

As mentioned the default start angle is at the x-axis, but you can change the start angle by
specifying a startangle parameter.
The startangle parameter is defined with an angle in degrees, default angle is 0:

Example
Start the first wedge at 90 degrees:

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])


mylabels =
["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels, startangle = 90)


plt.show()
Colors
You can set the color of each wedge with the colors parameter.
The colors parameter, if specified, must be an array with one value for each wedge:

Example
Specify a new color for each wedge:

import matplotlib.pyplot as plt


import numpy as np

y = np.array([35, 25, 25, 15])


mylabels =
["Apples", "Bananas", "Cherries", "Dates"]
mycolors = ["black", "hotpink", "b", "#4CAF50"]

plt.pie(y, labels = mylabels, colors =


mycolors)
plt.show()
Thank You…

You might also like