Agya Ram Verma_ Yatendra Kumar - Basic and Advance_ Phython Programming-Independently Published (2024)
Agya Ram Verma_ Yatendra Kumar - Basic and Advance_ Phython Programming-Independently Published (2024)
9 789391 383633
Basic and Advance
Phython Programming Language
Dr Agya Ram Verma was born Ayodhya, Uttar Pradesh, India. He received the B. Tech
degree in Electronic and Instrumentation Engineering from IET MJPRU Bareilly, UP,
India, in 2010. He completed the M.Tech. degree in Electronic and Communication
Engineering from the Indian Institute of Information Technology (IIIT), Design
and Manufacturing, Jabalpur, India. He received the PhD degree from Uttarakhand
Technical University, Dehradun, in 2019. He joined the Department of Electronics &
Communication Engineering, G. B. Pant Engineering College, Pauri Garhwal, India,
in 2013, as Assistant Professor. His research interest includes machine learning, signal
processing. He has published more than 35 research papers in refereed international
journals and conferences. He has published one Patent in 2021. He has published
one book on fundamental of machine learning form Sara book publication in 2021.
He also obtains one R&D Project and one Constancy Project. He is also reviewer of
many reputed international journals like Computer Methods in Biomechanics and
Biomedical Engineering: Imaging & Visualization (Taylor & Francis), IET Generation,
Transmission & Distribution, International Journal of Signal and Imaging Systems
Engineering (IJSISE), Journal of Intelligent & Fuzzy Systems, GUCON 2019 IEEE
Conference, India, Signal processing journal, Electronics Letters, IET.
Dr.Yatendra Kumar is former Head and Associate Professor, Department of
Electronics and Instrumentation Engineering, Faculty of Engineering and Technology,
Mahatma Jyotiba Phule Rohilkhand University, Bareilly, UP (India). He has completed
his B.Tech (Electronics and Instrumentation Engineering) in 1999 and M.Tech
(Instrumentation Engineering) from National Institute of Technology (Formerly known
as Regional Engineering College), Kurukshetra, Haryana in 2001. He has completed
his Ph.D. degree from Indian School of Mines (ISM), Dhanbad. He has more than
20 years of teaching experience. Besides, he has authored and co-authored several
research papers published in national and international journals. He is also reviewer
of many reputed international journals like IEEE Access, International Journal of
Electronics, Microwave and Optical Technologies Letter, International Journal of
Electronics and Communications(AEU) International Journal of RF and Computer
Aided Design (RFCAD) and International Journal of microwave and Technologies.
Dr. Sag Ram Verma received his B.Sc. in 2003 from Dr. R. M. L. Awadh University,
Ayodhya, India and M.Sc. in 2005 with Mathematics from Banaras Hindu University,
Varanasi, India. He received his Ph.D. in Applied Mathematics from Indian Institute
of Technology (BHU), Varanasi, India in year 2009. He is currently working as an
Assistant Professor in Mathematics, Gurukula Kangri (Deemed to be University),
Haridwar (UK) India since 2011. His research interest includes Mathematical
programming, Wavelet analysis and its applications. He has published more than 25
research papers in refereed international journals and conferences. He has guided 4
PhD student.
Basic and Advance
Phython Programming Language
Yatendra Kumar
Former Head and Associate Professor
Department of Electronics and Instrumentation Engineering
Faculty of Engineering and Technology
Mahatma Jyotiba Phule Rohilkhand University
Bareilly, Uttar Pradesh, India
© 2023, Publisher
ISBN: 978-93-91383-63-3 eISBN: 978-93-94490-49-9
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system
or transmitted in any form or by any means, including electronic, mechanical, photocopying
recording or otherwise without the prior written permission of the publisher or the copyright holder.
This book contains information obtained from authentic and highly reliable sources. Reasonable
efforts have been made to publish reliable data and information, but the author/s, editor/s and
publisher cannot assume responsibility for the validity, accuracy or completeness of all materials
or information published herein or the consequences of their use. The work is published with
the understanding that the publisher and author/s are not attempting to render any professional
services. The author/s, editor/s and publisher have attempted to trace and acknowledge the
copyright holders of all material reproduced in this publication and apologize to copyright
holders if permission and/or acknowledgements to publish in this form have not been taken. If
any copyrighted material has not been acknowledged, please write to us and let us know so that
we may rectify the error, in subsequent reprints.
Trademark Notice: NIPA, the NIPA logos and their presentations (the way they are written/
presented) in this book are the trademarks of the publisher and hence may not be used without
written permission, if copied or used without authorization, the infringer will be prosecuted as
per law.
NIPA also publishes books in a variety of electronic formats. Some content that appears in print
may not be available in electronic books, and vice versa.
Composed and Designed by NIPA.
Acknowledgements
Our debts in the writing of this book are many, and we spell them out now.
Bear with us. We acknowledge many in the ‘References’ section towards
the end of the book. We have tried our best but almost certainly failed to
recognize some of the others by not making proper notes. To any such creators
that we may have overlooked, our apologies. We have learned a great deal
from the writings of experts in the investor/trader community and the Python
community on online forums like stackoverflow.com, quora.com, and others
and are indebted to them.
Finally, we would like to thank all the students we have taught in the past
several years. A special thanks to those of you who endured our first few
iterations of the lectures before we learned how best to teach it. Dear students,
we exist because you exist. You have inspired us, challenged us, and pushed
us never to stop learning just to keep up with you. We hope you enjoy reading
this as much as we enjoyed writing it for you.
A.R. Verma
Y. Kumar
S.R. Verma
Preface
This book will introduce you to the python programming language. It’s aimed
at beginning programmers, but even if you have written programs before and
just want to add python to your list of languages.
The first eight chapters explain python’s basic and you should read them in
order. The later chapters show how Python is used in specific application
areas such as the web, database, networks, and so on, read them in any order
you like. Chapter 1 this chapter explain different basic topic related python
programming. Chapter 2 in this chapter define python operator. Chapter 3
in this chapter define looping statement. Chapter 4 in this chapter define
python function. Chapter 5 in this chapter explain string statement. Chapter
6 in this chapter define list in python programming. Chapter 7 in this chapter
explain tuple in python programming. Chapter 8 in this chapter explain
dictionary in python programming. Chapter 9 in this chapter explain numpy
in python programming. Chapter 10 in this chapter exaplain lambda function
in python programming. Chapter 11 in this chapter explain pandas in python
programming. Chapter 12 in this chapter explain python pandas functionality.
Chapter 12 in this chapter explain data frame basic functionality. Chapter 13
in this chapter explain python pandas statical functions. Chapter 14 in this
chapter explain python panda visualization. Chapter 15 in this chapter exaplain
data visualization in python programming. Chapter 16 in this chapter explain
object oriented programming. Chapter 17 in this chapter explain module
in python programming. Chapter 18 in this chapter explain python library.
Chapter 19 in this chapter explain turtle grapics in python programming.
Chapter 20 in this chapter explain brief tour of the standard libray.
A.R. Verma
Y. Kumar
S.R. Verma
Contents
Acknowledgements..................................................................................................v
Preface��������������������������������������������������������������������������������������������������������������� vii
11.3.4 Panel................................................................................... 90
11.4 Python Pandas Series...................................................................... 90
11.4.1 Create an Empty Series...................................................... 90
11.4.2 Create a Series From Ndarray.............................................91
11.5 Create a Series from Dictonary...................................................... 92
11.6 Create a Series from Scalar............................................................ 93
11.7 Accessing Data from Series with Position..................................... 93
11.8 Retrieve Data Using Label (Index)................................................. 94
11.9 Python Pandas - DataFrame........................................................... 95
11.9.1 Create DataFrame............................................................... 96
11.9.2 Create a DataFrame from Lists.......................................... 97
11.9.3 Create a DataFrame from Dict of ndarrays / Lists............. 98
10.9.4 Create a DataFrame from List of Dicts.............................. 99
11.9.5 Create a DataFrame from Dict of Series...........................100
11.9.6 Column Selection..............................................................101
11.9.7 Column Addition...............................................................101
11.9.8 Column Deletion...............................................................102
11.9.9 Row Selection, Addition, and Deletion.............................103
11.9.10 Selection by Label.............................................................103
11.9.11 Selection by Integer Location...........................................104
11.9.12 Slice Rows.........................................................................104
11.9.13 Addition of Rows...............................................................105
11.9.14 Deletion of Rows...............................................................105
11.10 Python Pandas - Panel...................................................................106
11.10.1 Create Panel.......................................................................106
11.11.2 Create an Empty Panel......................................................107
11.11.3 Selecting the Data from Panel...........................................108
12. Python Pandas: Basic Functionality...........................................111
12.1 Introduction Basic Functionality................................................... 111
12.2 Series Basic Functionality............................................................. 111
12.2.1 Axes...................................................................................112
12.2.2 Empty................................................................................112
12.2.3 Ndim..................................................................................113
12.2.4 Size....................................................................................113
xiv Basic and Advance Phython Programming Language
1.1 Introduction
Python is an interpreter, high level, general purpose programming language
developed by Guido Van Rossum and its first version was released in 1991.
There are two major Python versions: Python 2 and Python 3. Both are quite
different.
print(c)
output:11
Note: If any value print as it is the write inverted comma otherwise without
inverted comma.
Till the previous examples, We have just printed the values stored in variables
or directly printed the message. Now what if we want to print message along
with values? Have a look on the code below:
Example
a=5
b=10
c=a+b
print(“addition=”,c)
If extending the previous program to know more about print method we may
extend it as:
Example
a=5
b=10
c=a+b
print(“addition of”,a,”and”,b,”=”,c)
Input()
Python provides us the facility to take input from user using Input() function.
This function prompts the user to input a value.
Example:
Name=input(“Enter your Name”)
Print(Name)
Example:2
Name=input(“Enter your Name”)
Print(“Welcome Mr.”,Name)
Output: Welcome Mr.Anup Kumar
Note:Please note that the Input() accepts the input only in string format. So, if
any mathematcical calculation is to integer format. For converting the input to
integer format python provide us a function called: int()
Basic Concept of Python Programming 5
Example
a=int(input(“Enter 1st value:”))
b=int(input(“Enter 2nd value:”))
c=a+b
print(“addition=”,c)
1.8.1 Advantages
1. Presence of third-party modules
2. Extensive support libraries(NumPy for numerical calculations, Pandas
for data analytics etc)
3. Open source and community development
4. Versatile, Easy to read, learn and write
5. User-friendly data structures
6. High-level language
7. Dynamically typed language(No need to mention data type based on the
value assigned, it takes data type)
8. Object-oriented language
9. Portable and Interactive
10. Ideal for prototypes – provide more functionality with less coding
11. Highly Efficient(Python’s clean object-oriented design provides
enhanced process control, and the language is equipped with excellent
text processing and integration capabilities, as well as its own unit
testing framework, which makes it more efficient.)
12. (IoT)Internet of Things Opportunities
13. Interpreted Language
14. Portable across Operating systems
Basic Concept of Python Programming 7
1.8.2 Applications
1. GUI based desktop applications
2. Graphic design, image processing applications, Games, and Scientific/
computational Applications
3. Web frameworks and applications
4. Enterprise and Business applications
5. Operating Systems
6. Education
7. Database Access
8. Language Development
9. Prototyping
10. Software Development
2.1 Operators
Operators are those who perform some specific operation. Python has a wide
variety of operators. The various python operators are categorized into:
1. Arithmetic operators
2. Comparison/relational operators
3. Assignment operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operator
Example
x=5
If(type(x) is int):
print(“correct”)
else:
print(“incorrect”)
Example
x=5.2
If(type(x) is not int):
print(“correct”)
else:
print(“incorrect”)
12 Basic and Advance Phython Programming Language
Example
a=10
list=[1,2,3,4,5]
if(a in list)
print(“Yes a is present in the list.”)
else:
print(“no a is not present in the list”)
Example
a=1
list=[1,2,3,4,5]
if(a in list)
print(“Yes a is present in the list.”)
else:
print(“no a is not present in the list”)
Example
Let x=0000 0110
y = 0000 1000
now x&y (bitwise &) =0000 0000
x|y (bitwise |) = 0000 1110
x^y (bitwise XOR) = 0000 1110
Python Operators 13
div=a/b
print(“addition=”,add)
print(“subtraction=”,sub)
print(“multiplication=”,mul)
print(“division=”,div)
Example 2: Write a program to calculate
(a) Are of rectangle
(b) Perimeter of rectangle
(c) Area of square
(d) Perimeter of square
(e) Area of circle
(f) Circumference of circle
# Python Program to find Area of a Rectangle
width = float(input(‘Please Enter the Width of a Rectangle: ‘))
height = float(input(‘Please Enter the Height of a Rectangle: ‘))
# calculate the area
Area = width * height
# calculate the Perimeter
Perimeter = 2 * (width + height)
print(Area)
print(Perimeter)
# Python Program to find Area Of Circle using Radius
PI = 3.14
radius = float(input(‘ Please Enter the radius of a circle: ‘))
area = PI * radius * radius
circumference = 2 * PI * radius
print(area)
print(circumference)
Example 3: Write a program to swap values of two numbers.
a=int(input(“enter 1st num:”))
b=int(input(“enter 2nd num:”))
c=a
a=b
b=c
print(“value of a=”,a)
print(“value of b=”,b)
3
Looping Statement
3.1.3 If Statement
If is a bi-directional conditional control statement that checks the condition
and work according to that condition. A condition may have only two results:
16 Basic and Advance Phython Programming Language
-----------------
elif condition :
statement 1
-----------------
else:
statement 1
-----------------
Level 1 program
Example 1: write a program to check whether a number is odd/even.
Solution
a=int(input(“enter the number to check:”)
if (a%2==0):
print(“the number is even.”)
else:
print(“the number is odd.”)
Example 2: Write a program to check whether an age is able to voting or
not
Solution
a=int(input(“enter your age:”)
if (a>18):
print(“Eligible vote.”)
else:
print(“Eligible not vote.”)
Example 3: Write a program to find max between two numbers
Solution
a=int(input(“enter 1st num:”))
b=int(input(“enter 2nd num:”))
if (a>b):
print(“max no.”, a)
else:
print(“max no.”, b)
18 Basic and Advance Phython Programming Language
if (percent>=80):
print(“you have got grade A.”)
elif (percent>=60):
print(“you have got grade B.”)
elif (percent>=40):
print(“you have got grade C.”)
else:
print(“you have got grade D.”)
Initialization
This is the initialization of the counter variable using loop will be executed. In
other words, we can say that there must be some value from where to start and
this value is called initialization.
20 Basic and Advance Phython Programming Language
Condition
This is the condition up to which the loop will keep executing. Till this
condition is true, the loop body will keep executing and till the given condition
becomes false.
Increment/Decrement
To terminate a loop either the counter variable is increased or decrease by a
specified value. This is called Increment/Decrement.
Program Initialization Condition Increment/Decrement
Print 1 to 10 i=1 i<=10 I=i+1
Print 2 to 10 i=2 i<=10 I=i+2
Print 10 to 1 i=10 i>=10 I=i-1
Level 2 program
Example:Write a program to find sum of digits of a given number.
i=int(input(“enter number to find sum of digits”))
sum=0
while(i>0):
sum=sum+i%10
i=i//10
print(“sum of digits=sum”,sum)
Example:Write a program to find sum of square of digits of a given
number.
i=int(input(“enter number to find sum of square of digits”))
sum=0
while(i>0):
sum=sum+(i%10)*(i%10)
i=i//10
print(“sum of square of each digits=sum”,sum)
Looping Statement 23
i=i//10
if(sum==n):
print(“Armstrong”)
else:
print(“not Armstrong”)
Example: Write a program to find product of digits of a given number.
i=int(input(“enter number:”))
prod=1
while(i>0):
prod=prod*(i%10)
i=i//10
print(“product of digits=”,prod)
Example: Write a program to reverse a given number.
i=int(input(“enter number:”))
rev=0
while(i>0):
rev=(rev*10)+i%10
i=i//10
print(“reverse=”,rev)
Example: Write a program to check a number is palindrome or not.
i=int(input(“enter number:”))
rev=0
x=i
while(i>0):
rev=(rev*10)+i%10
i=i//10
if(x==rev):
print(“palindrome number”)
else:
print(“Not palindrome number”)
Example: Write a program to check a number is prime or not.
n=int(input(“enter number:”))
count=0
i=1
while(i<=n):
if(n%i==0):
count=count+1
i=i+1
Looping Statement 25
if(count==2):
print(“prime number”)
else:
print(“composite number”)
Example: Write a program to print factorial of a given number.
i=int(input(“enter number:”))
fac=1
while(i>0):
fac=fac*i
i=i-1
print(“Factorial=”,fac)
Example1: Write a program to print Fabonacci series up to a given
number.
n=int(input(“enter number:”))
x=0
y=1
z=0
while(z<=n):
print(z)
x=y
y=z
z=x+y
while(j<=i):
print(“i”,end=’’)
j=j+1
print()
i=i+1
Example3(1)
i=1
while(i<=5):
j=1
while(j<=i):
print(“j”,end=’’)
j=j+1
print()
i=i+1
Example : printing stars * in reverse angle triangle shape
i=1
while(i<=5):
b=1
while(b<=5-i):
print(“_”,end=’’)
b=b+1
j=1
while(j<=i):
print(“*”,end=””)
j=j+1
print()
i=i+1
Example 1: printing pyramid program
k=1
i=1
while(i<=5):
b=1
while(b<=5-i):
print(“_”,end=’’)
b=b+1
j=1
while(j<=k):
print(“*”,end=””)
Looping Statement 27
j=j+1
k=k+2
print()
i=i+1
Example 2(1)
k=1
i=1
while(i<=5):
b=1
while(b<=5-i):
print(“_”,end=’’)
b=b+1
j=1
while(j<=k):
print(k,end=””)
j=j+1
k=k+2
print()
i=i+1
Example3(1)
k=1
i=1
while(i<=5):
b=1
while(b<=5-i):
print(“_”,end=’’)
b=b+1
j=1
while(j<=k):
print(i,end=””)
j=j+1
k=k+2
print()
i=i+1
Example: print opposite pyramid shape
n=int(input(“enter no of row”))
i=1
While(n>0):
28 Basic and Advance Phython Programming Language
b=1
while(b<i):
print(“_”,end=””)
b=b+1
j=1
while(j<=(n*2)-i):
print(“*”,end=””)
j=j+1
print()
n=n-1
i=i+1
z=add(a,b)
print(“Addition=”,z)
c=a+b
return c
x=add()
print(“Addition=”,x)
print(i)
i=i+1
Output:1,2
Example:
i=0
while(i<=5):
i=i+1
if(i==3):
continue
print(i)
Output:1,2,4,5,6
5
String in Python Programming
output
s
h
y
a
m
Example:
name=”shyam”
for i in name:
print(i,end=””)
output: shyam
Example
Comparison
“a”==”a”
“ram”==”ram”
“a”!=”ram”
Comparison always according ASCII code.
String slicing:
String slicing returns the characters falling between indices n and m:
String at n, n+1,n+2,….till m-1. The syntax is:
String[start:end:step_value]
Example
1. a=”hello word”
print(a[4:-2])
output:o wor
2. a=”hello word”
print(a[6:],a[:6])
output:word hello
Note:6: by default last tak print karega, :6 by default 0 se start karega
Str[6:10] last 9 tak print karega,
Example:
a=”shyam kumar”
print(a.capitalize())
output:Shyam kumar
Example:
a=input(“enter you name:”)
for i in range(0,len(a)):
print(a[i])
Example: find reverse of a string
a=input(“enter string:”)
for i in range((len(a)-1),-1,-1):
Print(a[i],end=””)
Example: find reverse of a string
a=input(“enter string:”)
Print(a[-1::-1])
Example: find total no vowels and consonant in given string
a=input(“enter your name:”)
vowel=0
cons=0
for i in range(0,len(a)):
if(a[i]!=’’):
if(a[i]==”a” or a[i]==”e”or a[i] ==”i” or a[i]==”o” or a[i]==”u”
if(a[i]==”A” or a[i]==”E”or a[i] ==”I” or a[i]==”O” or
a[i]==”U”]:
vowel=vowel+1
else:
cons=cons+1
print(“total vowels=”,vowel)
print(“total consonant=”’cons)
3. find() # this function returns the lowest index in the string where the
substring is found, it returns the index where it is found and if not found
it returns -1
String in Python Programming 41
Example:
a=”RAM IS GOING TO MARKET”
b=”TO”
a.find(b,o,(len(a)-1))
output:13
Example: check a string is palindrome or not
a=input(“enter string:”)
b=a[-1::-1]
if(a==b):
print(“Palindrome string”)
else:
print(“Not Palindrome string”)
4. isalnum() # This return if the characters in the string are alphanumeric
(alphabets or numbers) and there is at least one character otherwise it
returns false
Example:
a=”ram123”
a.isalnum()
b=”hello”
b.isalnum()
c=”1234”
c.isalnum()
c=””
c.isalnum()
5. isdigit() # isalnum() # This return if all the characters in the string are
digits and there is at least one digitotherwise it returns false
Example:
a=”ram123”
a.isdigit()
b=”hell”
b.isdigit()
6. isspace() # This return true when there are only white spaces in the
string and there is at least one character. Otherwise it returns false.
Example:
a=” ”
a.isspace() #output True
6
List in Python Programming
a[0]=ram
a=[“ram”,1,”shyam”,12.5]
print(a)
print(a[0])
ram
Example:
a=[“ram”,10,”shyam”,12.5]
print(a[1])
a[1]=”Ramesh”
output : a=[ram,10,shyam,12.5]
print(a[1])
output : a=[ram,Ramesh,shyam,12.5]
Example:
a=[“ram”,10,”shyam”,12.5]
for i in a:
print(i)
1. len(list) # This method used to find total length of the list
Example
a=[“ram”,10,”shyam”,12.5]
b=len(a)
print(b)
2. max(list) # This method used to find max value
List in Python Programming 45
Example
a=[“ram”,10,”shyam”,12.5]
b=max(a)
print(b)
3. min(list) # This method used to find min value
Example
a=[“ram”,10,”shyam”,12.5]
b=max(a)
print(b)
Case 1: what if we have a list of string and integer values and we want to use
max function. In this case will produce an error message stating that string and
integer value comparison is not possible.
Case2: what if string value comparison is there. In such case, it will be
compared as a to z in ascending order.
Note: max or min compare for similar type elements in list
4. cmp(list1,list2) # This method is used to compare two list
Syntax:
cmp(list1,list2)
Returns: return 1 is list1 is greater than list2 return 0 if both the list are equal
returns -1 is list2 is greater than list1
There are some certain cases for comparison for two lists
Case1:
a. If both the list contains integers, then the comparison is done from left to
right. If we get a larger number at any particular index, that list becomes
greater and further comparison is stopped.
b. If all the elements in both the list are similar and one list is larger is size
the larger size list is greater.
c. And if both contain some value the lists are equal.
List1=[2,4,6,8]
List2=[2,4,6,9]
46 Basic and Advance Phython Programming Language
List3=[2,4,6,9,11]
List4=[2,4,6,8]
Print(“comparing list1 and list2:”)
Print(cmp(list1,list2)) #output -1
Print(“comparing list2 and list3:”)
Print(cmp(list2,list3)) #output -1
Print(“comparing list1 and list4:”)
Print(cmp(list1,list4)) #output 0
Case 2
a. When list contains multiple datatypes, in such case string is consider to
be greater than integer
b. The comparison in case of multiple data types is done with the sorted
case of comparison.
List1=[2,4,6,8]
List2=[2,4,6,’a’]
List3=[‘a’,’b’,’c’]
List4=[‘a’,’c’,’b’]
Print(“comparing list2 and list1:”)
Print(cmp(list2,list1)) #output 1
Print(“comparing list2 and list3:”)
Print(cmp(list2,list3)) #output -1
Print(“comparing list3 and list4:”)
Print(cmp(list3,list4)) #output -1
5. list.append(obj):This method is used to append (add) a passed object at
the end of the list. Note that the object is added to the last of the list.
Syntax:
list.append(obj)
Example
a=[“ram”,”shyam”,”sita”,”gita”]
List in Python Programming 47
a.append(“mita”)
print(a)
output: ram,shyam,sita,gita,mita
Example
a=[]
for i in range(10):
x=input(“enter item to add in the list:”)
a.append(x)
print(a)
6. list.count(obj):This method is used to count the frequency of a given
object.
Synatax:
list.count(obj)
Example
a=[“ram”,”shyam”,”sita”,”gita”]
x=a.count(“ram”)
print(“frequency=”,x)
Example
a=[]
for i in range(10):
x=input(“enter item to add in the list:”)
a.append(x)
x=input(“enter value whose frequency you want:”)
f=a.count(x)
print(“frequency of “,x,”is=”,f)
Note: you have to specific that what type of data you are going to search for
counting frequency. The type of input is the list determines the type of value
whose frequency you want to get.
7. list.index(obj):This method is used to find the index of the object/
element. This function returns the first index of the object/index if it is
found otherwise it returns an exceptions showing that the element is not
found.
Synatx: list.index(obj)
48 Basic and Advance Phython Programming Language
Example
a=[“ram”,”shyam”,”sita”,”gita”]
x=a.count(“ram”)
print(“index of ram=”,x)
Example
a=[]
for i in range(5):
x=input(“enter item:”)
a.append(x)
x=input(“enter value of index:”)
f=a.index(x)
print(“index = “,z)
8. list.insert(index,obj) :This method is used to inser an object/value at the
given index.
Syntax: list.insert(index,object)
Example
a=[5,”ram”,10]
a.insert(2,”shyam”)
print(a)
output:5,ram,shyam,10
Example
a=[]
for i in range(5):
x=input(“enter item:”)
a.append(x)
print(“orginal list is:”,a)
index=input(“enter index where you want to inser:”)
value=input(“enter value insert:”)
a.insert(index,value)
print(“list after insertion: “,a)
9. list.remove(obj) : This method is used to delete an object/value from te
given list. Note that it removes/deletes the first occurrence of the list.
Syntax: list.remove(object)
List in Python Programming 49
Example
a=[5,”ram”,10,”ravi”,10]
a.remove(10)
print(a)
output: 5,ram,ravi,10
Example
a=[]
for i in range(5):
x=input(“enter item:”)
a.append(x)
print(“orginal list is:”,a)
val=input(“enter value to remove:”)
a.remove (val)
print(“list after deletion: “,a)
10. list.reverse() : This method is used to reverse the elements present in the
list in place. Here the word , in place means that the list gets reversed itself.
Syntax: list.reverse()
Example
a=[5,”ram”,10,”ravi”,10]
a.reverse()
print(a)
output:10,ravi,10,ram,5
Example
a=[]
for i in range(5):
x=input(“enter item:”)
a.append(x)
print(“orginal list is:”,a)
a.reverse()
print(“list after reverse: “,a)
11. list.sort() : This method is used to sort the elements present in the list in
either ascending order or in descending order. The list gets sorted itself.
Note that the sorting in done with the similar data type, that means your list
should have similar types of data otherwise it will show error. By default
the sorting is done in the ascending order.
50 Basic and Advance Phython Programming Language
Syntax
1. List.sort(reverse=”False”) # ascending order,
2. List.sort(reverse=”True”) # descending order
Example
a=[]
for i in range(5):
x=input(“enter item:”)
a.append(x)
print(“orginal list is:”,a)
a.sort()
print(“list after sort: “,a)
Note: if you write here like:
c=a.sort()
print(c) #it is wrong because sort function ki value ko kahi copy
nahi kiya ja sakata hai.
12. list.pop(): this method is used to delete the last element from the list. Note
that this function deletes the last elements from the list one by one.
Syntax: list.pop()
Example
a=[5,2,8,3,7]
a.pop()
print()
output:5,2,8,3
flag=1
pos=i+1
break
if(flag==1):
print(“enter found at:”,”pos”,”position.”)
else:
print(“element not found=”)
Example: Program to count frequency of a given number
a=[]
size=int(input(“enter size of list:”)
for i in range(size):
val=int(input(“enter number:”))
a.append(val)
key=int(input(“enter number of frequency:”)
count=0
for i in range(size):
if(a[i]==key):
count=count+1
print(“Frequency count=”,count)
Example: Program to find max number in the list
a=[]
size=int(input(“enter size of list:”)
for i in range(size):
val=int(input(“enter number:”))
a.append(val)
max=a[0]
for i in range(size):
if(a[i]>max):
max=a[i]
print(“max number=”,max)
Example: Program to find min number in the list
a=[]
size=int(input(“enter size of list:”)
for i in range(size):
val=int(input(“enter number:”))
a.append(val)
min=a[0]
List in Python Programming 53
for i in range(size):
if(a[i]<min):
min=a[i]
print(“min number=”,min)
Example: Program to reverse the list itself.
a=[]
size=int(input(“enter size of list:”)
for i in range(size):
val=int(input(“enter number:”))
a.append(val)
i=0
j=size-1
while(i<j):
t=a[i]
a[i]=a[j]
a[j]=t
i=i+1
j=j-1
print(“List after reverse=”)
for i in range(size):
print(a[i])
Example: Program to Find Second Max, Second Min
a=[]
size=int(input(“enter size of list:”)
for i in range(size):
val=int(input(“enter number:”))
a.append(val)
minval=min(a)
print(“min value in the list is:”, minval)
a.remove(minval)
smin=min(a)
print(“second min value in the list=”,smin)
Max number
a=[]
size=int(input(“enter size of list:”)
for i in range(size):
val=int(input(“enter number:”))
a.append(val)
54 Basic and Advance Phython Programming Language
a.sort()
print(“max num:”, a[size-1])
print(“second max num:”, a[size-2])
7
Tuple in Python Programming
a.index(30)
output:2
Note:it will return 1st value index
5. count()
count() method returns the frequency of given element.
Syntax: tuple.count(item)
Example:
a=(10,20,30,45,20,15)
a.count(30)
6. tuple()
This method is used as a constructor which is used to create tuples from
different types of values.
Syantax: tuple(sequence)
Example:
1. Creating empty tuple
tuple()
2.Creating tuple from list
t=tuple([1,2,3])
output: (1,2,3)
3.Creating tuple from string
tuple1=tuple(“xyz”)
Output: (‘a’,’b’,’c’)
4.Creating tuple from key of dictionary
tuple1=tuple({1:’m’,2:’n’})
tuple1
output: (1,2)
Example
You need to convert the tuple into a list to be able to change it:
x=(‘apple’,’banana’,’cherry’)
y=list(x)
y[1]=’kiwi’
x=tuple(y)
print(x)
Check if item exists: To determine if a specified item is present in a tuple use
the “in” keyword.
Example
tuple1=(‘ram’,’shyam’,’sita’,’gita’)
if ‘ram’ in tuple1:
print(“yes the element is present in the tuple”)
else:
print(“no element is not present in the tuple”)
Add items
• Once a tuple is created, you cannot add items to it. Tuple are unchangeable.
• You cannot add items to a tuple
Example
tuple1=(‘apple’,’banana’,’cherry’)
tuple1[3]=’orange’ #this will raise an error
print(tuple1)
Delete tuple elements:
Removing individual elements of the tuple is not possible. To remove entire
tuple, just use the del statement.
Example
tuple1=(‘ram’,’shyam’,’sita’,’gita’)
print(tuple1)
del(tuple1)
print(“after deleting tuple”)
print(tuple1) # error show
8
Dictionary in Python Programming
Example
dict1={‘brand’:’Suzuki’,’model’:’dzire’,’year’:2020}
x=len(dict1)
2. Removing items # pop() :this method removes the element with specified
key name
Example
dict1={‘brand’:’Suzuki’,’model’:’dzire’,’year’:2020}
print(dict1)
dict1.pop(‘model’)
print(dict1)
output:
{‘brand’:’Suzuki’,’model’:’dzire’,’year’:2020}
{‘brand’:’Suzuki’ ,’year’:2020}
3. popitem(): #this method removes the last element of the dictionary. But
the in the version before 3.7 it was used to remove the
Example
dict1={‘brand’:’Suzuki’,’model’:’dzire’,’year’:2020}
print(dict1)
dict1.popitem()
print(dict1)
output:
{‘brand’:’Suzuki’,’model’:’dzire’,’year’:2020}
{‘brand’:’Suzuki’,’model’:’dzire’}
Example
dict1={‘brand’:’Suzuki’,’model’:’dzire’,’year’:2020}
print(dict1)
dict1.clear()
print(dict1)
output:
{}
output
setdefault() #
• The setdefault method returns the value of the item with the specified
key.
• If the key does not exist, it inserts the key, with the specified value.
Example
dict1={‘brand’:’Suzuki’,’model’:’dzire’,’year’:2020}
x=dict1.setdefault(‘brand’,’toyota’)
print(x)
output:
since ‘brand’ key is already present so it will return the value of this
key.
suzuki
Example
dict1={‘brand’:’Suzuki’,’model’:’dzire’,’year’:2020}
x=dict1.setdefault(‘place’,’new delhi’)
print(x)
output:
since ‘place’ key is not exist present in the dict1, it will insert this key
with value and then the respective value “new delhi” will assigned to
x and so “new delhi” will get printed.
Update()
The update() method inserts the specified items to the dictionary.
dict1={‘brand’:’Suzuki’,’model’:’dzire’,’year’:2020}
x=dict1.update(‘color’,’white’)
print(x)
9
Numpy in Python Programming
We can do it directly:
import numpy as np
myarr=np.array(a=[[1,2,3,4,5],[4,5,6],[7,8,9]])
myarr
3. Eye function
This function creates an array with all the diagonal elements as 1 and rest as
0 (in a square matrix). In case of a non-square matrix the values are still 1 for
diagonal (up to which it can draw diagonal) and rest are zero.
Example
import numpy as np
arr=np.eye(3)
70 Basic and Advance Phython Programming Language
output:
1 0 0
0 1 0
0 0 1
Example
import numpy as np
arr=np.eye(3,4)
output:
1 0 0 0
0 1 0 0
0 0 1 0
4. Diag function
This function creates a two dimensional array with all the diagonal elements as
the given value and rest as 0 (in a square matrix).
Example
import numpy as np
arr=np.diag([1,5,3,7])
output:
1 0 0 0
0 5 0 0
0 0 3 7
5. Randint()
This function is used to generate a random number between a given range.
Syntax:
Rand(min,max,total_values)
Example:
Import numpy as np
arr=np.random.randint(1,10,3)
output:
may be any 3 number from 1 to 9.
Numpy in Python Programming 71
6. rand()
This function is used to generate a random values between 0 to 1.
Syntax:
rand(number_of_values)
example:
import numpy as np
arr=np.random.rand(5)
output: may be any 5 number from 0 to 1.
from index 2 to 3.
print(arr1)
Example
import numpy as np
matrix=[]
row=int(input(“enter number of row:”))
col=int(input(“enter number of col:”))
for i in range(row):
a=[]
for j in range(col):
val= row=int(input(“enter number:”))
a.append(val)
matrix.append(a)
for i in range(row):
for j in range(col):
print(arr[i][j],end=” ”)
print()
print(type(arr))
Example
a=np.array([10,20,30,40,50,60,70,80])
slicing=a[3:6]
slicing[:]=0
print(a)
output: 10,20,30,0,0,0,70,80
Example
a=np.array([10,20,30,40,50,60,70,80])
slicing=a[3:6].copy()
slicing[:]=0
print(a)
output: 10,20,30,40,50,60,70,80
Note : this means the original array has not been updated.
Note: In numpy array divide by zero gives infinity and not any error.
print(matrix)
np.sum(matrix, axis=1) # find row wise sum
np.min(matrix, axis=1) # find row wise win
np.max(matrix, axis=0) # find col wise max
np.cumsum(matrix) #cumulative sum
np.cumsum(matrix, axis=0) #cumulative sum
Example
import numpy as np
np.random.seed(122)
matrix=np.random.randint(1,21,10)
print(matrix)
np.random.shuffle(arr) #shuffles the array elements
np.unique(arr) #display unique number of the array
np.unique(arr).size #count the unique count of the elements
Example
import numpy as np
np.random.seed(122)
matrix=np.random.randint(1,21,10)
print(matrix)
np.unique(arr, return_index=True, return_counts=true)
#returns three array
1. The array with unique values
2. The array with respective index values
3. The array with counting of frequency
Example
import numpy as np
np.random.seed(122)
arr1=np.random.randint(1,21,9).reshape(3,3)
arr2=np.random.randint(31,51,9).reshape(3,3)
print(arr1)
print(arr2)
np.hstack((arr1,arr2)) #horizontally arranges the matrix
np.vstack((arr1,arr2)) #vertically arranges the matrix
Solution
Q 1.Write statement to import numpy
Answer
import numpy as np
Q 2. Create an array using numpy
Answer
import numpy as np
arr=np.array([1,2,3,4,5])
print(arr)
Q 3. Create an array of 10 random integers
Answer
import numpy as np
arr=np.random.randint(1,100,10)
print(arr)
Q 4. Create an array of elements from 10-20
Answer
import numpy as np
arr=np.arange(10,21)
print(arr)
Q 5.Create an array which contains value 5 times
Answer
import numpy as np
arr=np.ones()*5
print(arr)
Q 6. Create a one dimensional array and covert that into 3*3 matrix
Answer
import numpy as np
arr=np.arange(1,10).reshape(3,3)
print(arr)
Numpy in Python Programming 79
Q 7. Create an array and then convert all the even numbers with o
Answer
import numpy as np
arr=np.arange(1,11)
arr[arr%2==0]=0
print(arr)
Q 8. Create a 2D array of size 3*3 but all the elements should be between
0 and 1.
Answer
import numpy as np
arr=np.random.rand(9).reshape(3,3)
print(arr)
Q 9. Perform the following slicing:
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output
6 7
10 11
14 15
Concatenate 2D array horizontally and vertically
Answer
import numpy as np
arr1=np.arange(1,17).reshape(4,4)
arr2=arr1[1:,1:3]
print(arr2)
Q10. Concatenate 2D array horizontally and vertically
Answer
80 Basic and Advance Phython Programming Language
import numpy as np
arr1=np.arange(1,10).reshape(3,3)
arr2= np.arange(10,19).reshape(3,3)
np.hstack((arr1,arr2))
Answer
import numpy as np
arr1=np.arange(1,10).reshape(3,3)
arr2= np.arange(10,19).reshape(3,3)
np.vstack((arr1,arr2))
Searchsorted()
This method performs a binary search in the array, and returns the index
where the specified value would be inserted to maintain the search order.
Example
import numpy as np
a=np.array([2,5,8,9,13])
result=a.searchsorted(a,7,side=’right’)
print(result)
10
Lambda Function
in Python Programming
if x<18:
return False
else:
return True
adults=list(filter(myfunc, ages))
for x in adults:
print(x)
OR using lambda function
ages=[5,12,17,18,24,32]
adults=filter(lambda a:a>18, ages)
for x in adults:
print(x)
Note: filter function use a function and list of values
Example
val=[5,12,17,18,24,32]
def myfunc(x):
if x%2==0
return True
else:
return False
adults=list(filter(myfunc, val))
for x in even:
print(x)
OR using lambda function
val=[5,12,17,18,24,32]
even=filter(lambda a:a%2==0, val)
for x in even:
print(x)
return x*x
adults=filter(myfunc, ages)
for x in adults:
print(x)
squares=map(myfunc1, adults)
for x in squares:
print(x)
print(“addition=”,add)
OR using lambda function
import functools
val = [1, 3, 5, 6, 2]
add-reduce(lambda a,b, a+b, val)
# using reduce to compute sum of list
print(“addition=: “, add)
Example
import functools
def myfunc(a,b):
if a>b:
return a
else:
return b
val=[1,2,3,4,5]
max=reduce(myfunc,val)
print(“max=”, max)
OR using lambda function
import functools
val=[1,2,3,4,5]
max=reduce(lambda a,b: a if a>b else b, val)
print(“max=” max)
11
Pandas in Python Programming
11.1 Introduction
Pandas is an open-source Python Library providing high-performance
data manipulation and analysis tool using its powerful data structures. The
name Pandas is derived from the word Panel Data – an Econometrics from
Multidimensional data.
In 2008, developer Wes McKinney started developing pandas when in need of
high performance, flexible tool for analysis of data.
Prior to Pandas, Python was majorly used for data munging and preparation. It
had very little contribution towards data analysis. Pandas solved this problem.
Using Pandas, we can accomplish five typical steps in the processing and
analysis of data, regardless of the origin of data — load, prepare, manipulate,
model, and analyze.
Python with Pandas is used in a wide range of fields including academic and
commercial domains including finance, economics, Statistics, analytics, etc.
Building and handling two or more dimensional arrays is a tedious task, burden
is placed on the user to consider the orientation of the data set when writing
functions. But using Pandas data structures, the mental effort of the user is
reduced.
For example, with tabular data (DataFrame) it is more semantically helpful to
think of the index (the rows) and the columns rather than axis 0 and axis 1.
Mutability
All Pandas data structures are value mutable (can be changed) and except
Series all are size mutable. Series is size immutable.
Pandas in Python Programming 89
Note − DataFrame is widely used and one of the most important data
structures. Panel is used much less.
11.3.1 Series
Series is a one-dimensional array like structure with homogeneous data. For
example, the following series is a collection of integers 10, 23, 56,
10 23 56 17 52 61 73 90 26 72
Key Points
• Homogeneous data
• Size Immutable
• Values of Data Mutable
11.3.2 DataFrame
DataFrame is a two-dimensional array with heterogeneous data. For example,
Name Age Gender Rating
steve 32 Male 3.45
lia 28 Female 4.6
vin 45 Male 3.9
The table represents the data of a sales team of an organization with their
overall performance rating. The data is represented in rows and columns. Each
column represents an attribute and each row represents a person.
Key Points
• Heterogeneous data
• Size Mutable
• Data Mutable
90 Basic and Advance Phython Programming Language
11.3.4 Panel
Panel is a three-dimensional data structure with heterogeneous data. It is
hard to represent the panel in graphical representation. But a panel can be
illustrated as a container of DataFrame.
Key Points
• Heterogeneous data
• Size Mutable
• Data Mutable
Example
#import the pandas library and aliasing as pd
import pandas as pd
s = pd.Series()
print(s)
Its output is as follows:
Series([], dtype: float64)
Example
Retrieve multiple elements using a list of index label values.
import pandas as pd
s = pd.Series([1,2,3,4,5],index = [‘a’,’b’,’c’,’d’,’e’])
#retrieve multiple elements
Print(s[[‘a’,’c’,’d’]])
Its output is as follows :
a 1
c 3
d 4
dtype: int64
Example
If a label is not contained, an exception is raised.
import pandas as pd
s = pd.Series([1,2,3,4,5],index = [‘a’,’b’,’c’,’d’,’e’])
#retrieve multiple elements
Print(s[‘f’])
Its output is as follows :
…
KeyError: ‘f’
Structure
Let us assume that we are creating a data frame with student’s data.
Regd.No Name Marks%
1000 Shyam 78.2
1001 Raj 68.5
1002 Papu 56.8
1003 Sita 86.4
1004 Geeta 49.3
pandas.DataFrame
A pandas DataFrame can be created using the following constructor −
pandas.DataFrame( data, index, columns, dtype, copy)
The parameters of the constructor are as follows :
S.No. Parameter & Description
1 data
data takes various forms like ndarray, list, constants
2 index
Index values must be unique and hashable, same length as data. Default
np.arrange(n) if no index is passed.
3 columns
For column labels, the optional default syntax is - np.arange(n). This is only true if
no index is passed.
4 dtype
dtype is for data type. If None, data type will be inferred
5 copy
Copy data. Default False
0 1
1 2
2 3
3 4
4 5
Example
import pandas as pd
data = [[‘Alex’,10],[‘Bob’,12],[‘Clarke’,13]]
df = pd.DataFrame(data,columns=[‘Name’,’Age’])
print(df)
Its output is as follows :
Name Age
0 Alex 10
1 Bob 12
2 Clarke 13
98 Basic and Advance Phython Programming Language
Example
import pandas as pd
data = [[‘Alex’,10],[‘Bob’,12],[‘Clarke’,13]]
df = pd.DataFrame(data,columns=[‘Name’,’Age’],dtype=float)
print df
Its output is as follows:
Name Age
0 Alex 10.0
1 Bob 12.0
2 Clarke 13.0
Note − Observe, the dtype parameter changes the type of Age column to
floating point.
df[‘three’]=pd.Series([10,20,30],index=[‘a’,’b’,’c’])
print df
print (“Adding a new column using the existing columns in DataFrame:”)
df[‘four’]=df[‘one’]+df[‘three’]
print(df)
Its output is as follows:
Adding a new column by passing as Series:
one two three
a 1.0 1 10.0
b 2.0 2 20.0
c 3.0 3 30.0
d NaN 4 NaN
Adding a new column using the existing columns in DataFrame:
one two three four
a 1.0 1 10.0 11.0
b 2.0 2 20.0 22.0
c 3.0 3 30.0 33.0
d NaN 4 NaN NaN
df.pop(‘two’)
print(df)
Its output is as follows :
Our dataframe is:
one three two
a 1.0 10.0 1
b 2.0 20.0 2
c 3.0 30.0 3
d NaN NaN 4
Deleting the first column using DEL function:
three two
a 10.0 1
b 20.0 2
c 30.0 3
d NaN 4
Deleting another column using POP function:
three
a 10.0
b 20.0
c 30.0
d NaN
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
Example
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:
Item1 Item2
0 -0.128637 -1.047032
1 0.896681 -0.557322
2 0.571668 0.431953
3 -0.144234 1.302466
12
Python Pandas
Basic Functionality
Let us now create a Series and see all the above tabulated attributes operation
Example
import pandas as pd
import numpy as np
#Create a series with 100 random numbers
s = pd.Series(np.random.randn(4))
print(s)
112 Basic and Advance Phython Programming Language
12.2.1 Axes
Returns the list of the labels of the series.
Example
import pandas as pd
import numpy as np
#Create a series with 100 random numbers
s = pd.Series(np.random.randn(4))
print (“The axes are:”)
print s.axes
Its output is as follows :
The axes are:
[RangeIndex(start=0, stop=4, step=1)]
The above result is a compact format of a list of values from 0 to 5, i.e.,
[0,1,2,3,4].
12.2.2 Empty
Returns the Boolean value saying whether the Object is empty or not. True
indicates that the object is empty.
Example
import pandas as pd
import numpy as np
#Create a series with 100 random numbers
s = pd.Series(np.random.randn(4))
print (“Is the Object empty?”)
print s.empty
Its output is as follows:
Is the Object empty?
False
Python Pandas Basic Functionality 113
12.2.3 Ndim
Returns the number of dimensions of the object. By definition, a Series is a 1D
data structure, so it returns
Example
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(4))
print(s)
print (“The dimensions of the object:”)
print s.ndim
Its output is as follows:
0 0.175898
1 0.166197
2 -0.609712
3 -1.377000
dtype: float64
The dimensions of the object: 1
12.2.4 Size
Returns the size(length) of the series.
Example
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(2))
print s
print (“The size of the object:”)
print s.size
Its output is as follows :
0 3.078058
1 -1.207803
dtype: float64
The size of the object:
2
114 Basic and Advance Phython Programming Language
12.2.5 Values
Returns the actual data in the series as an array.
Example
import pandas as pd
import numpy as np
#Create a series with 4 random numbers
s = pd.Series(np.random.randn(4))
print(s)
print (“The actual data series is:”)
print s.values
Its output is as follows:
0 1.787373
1 -0.605159
2 0.180477
3 -0.140922
dtype: float64
The actual data series is:
[ 1.78737302 -0.60515881 0.18047664 -0.1409218 ]
Let us now create a DataFrame and see all how the above mentioned
attributes operate.
12.3.1 Example
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {‘Name’:pd.Series([‘Tom’,’James’,’Ricky’,’Vin’,’Steve’,’Smith’,’Jack’]),
‘Age’:pd.Series([25,26,25,23,30,29,23]),
‘Rating’:pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print (“Our data series is:”)
print df
Python Pandas Basic Functionality 117
12.3.2 T (Transpose)
Returns the transpose of the DataFrame. The rows and columns will
interchange.
Example
import pandas as pd
import numpy as np
# Create a Dictionary of series
d = {‘Name’:pd.Series([‘Tom’,’James’,’Ricky’,’Vin’,’Steve’,’Smith’,’Jack’]),
‘Age’:pd.Series([25,26,25,23,30,29,23]),
‘Rating’:pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
# Create a DataFrame
df = pd.DataFrame(d)
print (“The transpose of the data series is:”)
print df.T
Its output is as follows:
The transpose of the data series is:
0 1 2 3 4 5 6
Age 25 26 25 23 30 29 23
Name Tom James Ricky Vin Steve Smith Jack
Rating 4.23 3.24 3.98 2.56 3.2 4.6 3.8
12.3.3 Axes
Returns the list of row axis labels and column axis labels.
Example
import pandas as pd
import numpy as np
118 Basic and Advance Phython Programming Language
12.3.4 Dtypes
Returns the data type of each column.
Example
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {‘Name’:pd.Series([‘Tom’,’James’,’Ricky’,’Vin’,’Steve’,’Smith’,’Jack’]),
‘Age’:pd.Series([25,26,25,23,30,29,23]),
‘Rating’:pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print (“The data types of each column are:”)
print df.dtypes
Its output is as follows:
The data types of each column are:
Age int64
Name object
Rating float64
dtype: object
12.3.5 Empty
Returns the Boolean value saying whether the Object is empty or not; True
indicates that the object is empty.
Python Pandas Basic Functionality 119
Example
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {‘Name’:pd.Series([‘Tom’,’James’,’Ricky’,’Vin’,’Steve’,’Smith’,’Jack’]),
‘Age’:pd.Series([25,26,25,23,30,29,23]),
‘Rating’:pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print (“Is the object empty?”)
print df.empty
Its output is as follows:
Is the object empty?
False
12.3.6 Ndim
Returns the number of dimensions of the object. By definition, DataFrame is
a 2D object.
Example
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {‘Name’:pd.Series([‘Tom’,’James’,’Ricky’,’Vin’,’Steve’,’Smith’,’Jack’]),
‘Age’:pd.Series([25,26,25,23,30,29,23]),
‘Rating’:pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print (“Our object is:”)
print df
print (“The dimension of the object is:”)
print df.ndim
Its output is as follows:
Our object is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
120 Basic and Advance Phython Programming Language
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
The dimension of the object is:
2
12.3.7 Shape
Returns a tuple representing the dimensionality of the DataFrame. Tuple
(a,b), where a represents the number of rows and b represents the number of
columns.
Example
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {‘Name’:pd.Series([‘Tom’,’James’,’Ricky’,’Vin’,’Steve’,’Smith’,’Jack’]),
‘Age’:pd.Series([25,26,25,23,30,29,23]),
‘Rating’:pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print (“Our object is:”)
print df
print (“The shape of the object is:”)
print df.shape
Its output is as follows:
Our object is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
The shape of the object is:
(7, 3)
Python Pandas Basic Functionality 121
12.3.8 Size
Returns the number of elements in the DataFrame.
Example
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {‘Name’:pd.Series([‘Tom’,’James’,’Ricky’,’Vin’,’Steve’,’Smith’,’Jack’]),
‘Age’:pd.Series([25,26,25,23,30,29,23]),
‘Rating’:pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print (“Our object is:”)
print df
print (“The total number of elements in our object is:”)
print df.size
Its output is as follows:
Our object is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
The total number of elements in our object is:
21
12.3.9 Values
Returns the actual data in the DataFrame as an NDarray.
Example
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {‘Name’:pd.Series([‘Tom’,’James’,’Ricky’,’Vin’,’Steve’,’Smith’,’Jack’]),
‘Age’:pd.Series([25,26,25,23,30,29,23]),
‘Rating’:pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
122 Basic and Advance Phython Programming Language
#Create a DataFrame
df = pd.DataFrame(d)
print (“Our object is:”)
print df
print (“The actual data in our data frame is:”)
print df.values
Its output is as follows:
Our object is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
The actual data in our data frame is:
[[25 ‘Tom’ 4.23]
[26 ‘James’ 3.24]
[25 ‘Ricky’ 3.98]
[23 ‘Vin’ 2.56]
[30 ‘Steve’ 3.2]
[29 ‘Smith’ 4.6]
[23 ‘Jack’ 3.8]]
df = pd.DataFrame(d)
print (“Our data frame is:”)
print df
print (“The first two rows of the data frame is:”)
print df.head(2)
Its output is as follows:
Our data frame is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
2 25 Ricky 3.98
3 23 Vin 2.56
4 30 Steve 3.20
5 29 Smith 4.60
6 23 Jack 3.80
The first two rows of the data frame is:
Age Name Rating
0 25 Tom 4.23
1 26 James 3.24
tail() returns the last n rows (observe the index values). The default number
of elements to display is five, but you may pass a custom number.
Example
import pandas as pd
import numpy as np
#Create a Dictionary of series
d = {‘Name’:pd.Series([‘Tom’,’James’,’Ricky’,’Vin’,’Steve’,’Smith’,’Jack’]),
‘Age’:pd.Series([25,26,25,23,30,29,23]),
‘Rating’:pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
#Create a DataFrame
df = pd.DataFrame(d)
print (“Our data frame is:”)
print df
print (“The last two rows of the data frame is:”)
print df.tail(2)
124 Basic and Advance Phython Programming Language
Percent_change
Series, DatFrames and Panel, all have the function pct_change(). This
function compares every element with its prior element and computes the
change percentage.
Example
import pandas as pd
import numpy as np
s = pd.Series([1,2,3,4,5,4])
print s.pct_change()
df = pd.DataFrame(np.random.randn(5, 2))
print(df.pct_change())
Its output is as follows:
0 NaN
1 1.000000
2 0.500000
3 0.333333
4 0.250000
5 -0.200000
dtype: float64
0 1
0 NaN NaN
1 -15.151902 0.174730
2 -0.746374 -1.449088
126 Basic and Advance Phython Programming Language
3 -3.582229 -3.165836
4 15.601150 -1.860434
By default, the pct_change() operates on columns; if you want to apply the
same row wise, then use axis=1() argument.
13.1.1 Covariance
Covariance is applied on series data. The Series object has a method cov to
compute covariance between series objects. NA will be excluded automatically.
Cov Series
Example
import pandas as pd
import numpy as np
s1 = pd.Series(np.random.randn(10))
s2 = pd.Series(np.random.randn(10))
print(s1.cov(s2))
Its output is as follows:
-0.12978405324
Covariance method when applied on a DataFrame, computes cov between all
the columns.
Example
import pandas as pd
import numpy as np
frame = pd.DataFrame(np.random.randn(10, 5), columns=[‘a’, ‘b’, ‘c’, ‘d’,
‘e’])
print frame[‘a’].cov(frame[‘b’])
print(frame.cov())
Its output is as follows:
-0.58312921152741437
a b c d e
a 1.780628 -0.583129 -0.185575 0.003679 -0.136558
b -0.583129 1.297011 0.136530 -0.523719 0.251064
c -0.185575 0.136530 0.915227 -0.053881 -0.058926
d 0.003679 -0.523719 -0.053881 1.521426 -0.487694
e -0.136558 0.251064 -0.058926 -0.487694 0.960761
Note − Observe the cov between a and b column in the first statement and
the same is the value returned by cov on DataFrame.
Python Pandas Statistical Functions 127
13.1.2 Correlation
Correlation shows the linear relationship between any two array of values
(series). There are multiple methods to compute the correlation like
pearson(default), spearman and kendall.
Example
import pandas as pd
import numpy as np
frame = pd.DataFrame(np.random.randn(10, 5), columns=[‘a’, ‘b’, ‘c’, ‘d’,
‘e’])
print frame[‘a’].corr(frame[‘b’])
print(frame.corr())
Its output is as follows:
-0.383712785514
a b c d e
a 1.000000 -0.383713 -0.145368 0.002235 -0.104405
b -0.383713 1.000000 0.125311 -0.372821 0.224908
c -0.145368 0.125311 1.000000 -0.045661 -0.062840
d 0.002235 -0.372821 -0.045661 1.000000 -0.403380
e -0.104405 0.224908 -0.062840 -0.403380 1.000000
If any non-numeric column is present in the DataFrame, it is excluded
automatically.
e 5.0
dtype: float64
Rank optionally takes a parameter ascending which by default is true; when
false, data is reverse-ranked, with larger values assigned a smaller rank.
Rank supports different tie-breaking methods, specified with the method
parameter −
• average − average rank of tied group
• min − lowest rank in the group
• max − highest rank in the group
• first − ranks assigned in the order they appear in the array
14
Python Pandas
Visualization
We can plot one column versus another using the x and y keywords.
Plotting methods allow a handful of plot styles other than the default line plot.
These methods can be provided as the kind keyword argument to plot(). These
include −
• bar or barh for bar plots
• hist for histogram
• box for boxplot
• ‘area’ for area plots
• ‘scatter’ for scatter plots
Example
import pandas as pd
df = pd.DataFrame(np.random.rand(10,4),columns=[‘a’,’b’,’c’,’d’)
df.plot.bar(stacked=True)
Its output is as follows
14.1.2 Histograms
Histograms can be plotted using the plot.hist() method. We can specify
number of bins.
Example
import pandas as pd
import numpy as np
df = pd. Data Frame ({‘a’:np.random.randn(1000)+1,’b’:np.random.randn
(1000),’c’:
np.random.randn(1000) - 1}, columns=[‘a’, ‘b’, ‘c’])
df.plot.hist(bins=20)
Its output is as follows:
To plot different histograms for each column, use the following code
Example
import pandas as pd
import numpy as np
df=pd.DataFrame({‘a’:np.random.randn(1000)+1,’b’:np.random.
randn(1000),’c’:
np.random.randn(1000) - 1}, columns=[‘a’, ‘b’, ‘c’])
df.diff.hist(bins=20)
Python Pandas Visualization 133
15.3 Pyplot
1. Pyplot is a collection of command type functions that is used for data
visualization. Its is available inside matplotlib library.
2. Pyplot interface provides many method for 2D plotting of data using
which we can draw different types of 2D graphs/charts. We can draw
different types of graphs/charts using pyplot methods i.e. plot(), bar()
etc.
138 Basic and Advance Phython Programming Language
3. Multiple types of charts graphs can be plotted using pyplot like chart,
bar chart, pie chart, scattered chart, histogram etc.
4. To use pyplot we can have to import matplotlib which can be done by
two types
(i) Import matplotlib
(ii) Import matplotlib.pyplot as plt
Example
import matplotlib.pyplot as plt
x=[5,10,15,20,25]
y=[10,14,7,15,16]
plt.plot(x,y, color=’r’,marker=’*’,
markeredgecolor=’b’,markersize=8,linewidth=10,linestyle=”dotted”)
plt.show()
Output:
Example
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3,4,5,6]
# corresponding y axis values
y = [2,4,1,5,2,6]
# plotting the points
plt.plot(x, y, color=’green’, linestyle=’dashed’, linewidth = 3,
marker=›o›, markerfacecolor=›blue›, markersize=12)
# setting x and y axis range
plt.ylim(1,8)
plt.xlim(1,8)
# naming the x axis
plt.xlabel(‘x - axis’)
# naming the y axis
plt.ylabel(‘y - axis’)
140 Basic and Advance Phython Programming Language
Note:
As you can see, we have done several customizations like:
• setting the line-width, line-style, line-color.
• setting the marker, marker’s face color, marker’s size.
• overriding the x and y-axis range. If overriding is not done, pyplot
module uses the auto-scale feature to set the axis range and scale.
x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]
# second plot with x1 and y1 data
plt.plot(x1, y1, ‘-.’)
plt.xlabel(“X-axis data”)
plt.ylabel(“Y-axis data”)
plt.title(‘multiple plots’)
plt.show()
Output
Example
import matplotlib.pyplot as plt
# line 1 points
x1 = [1,2,3]
y1 = [2,4,1]
# plotting the line 1 points
plt.plot(x1, y1, label = “line 1”)
# line 2 points
x2 = [1,2,3]
y2 = [4,1,3]
# plotting the line 2 points
plt.plot(x2, y2, label = “line 2”)
# naming the x axis
plt.xlabel(‘x - axis’)
# naming the y axis
plt.ylabel(‘y - axis’)
# giving a title to my graph
142 Basic and Advance Phython Programming Language
• Note: Here, we plot two lines on the same graph. We differentiate between
them by giving them a name(label) which is passed as an argument of
the .plot() function.
• The small rectangular box giving information about the type of line
and its color is called a legend. We can add a legend to our plot using
.legend() function.
# plot title
plt.title(‘My bar chart!’)
# function to show the plot
plt.show()
Output
Note
• Here, we use plt.bar() function to plot a bar chart.
• x-coordinates of the left side of bars are passed along with the heights of
bars.
• you can also give some names to x-axis coordinates by defining tick_
labels
Note:
• Here, we plot a pie chart by using plt.pie() method.
• First of all, we define the labels using a list called activities.
• Then, a portion of each label can be defined using another list called
slices.
• Color for each label is defined using a list called colors.
• shadow = True will show a shadow beneath each label in pie chart.
• startangle rotates the start of the pie chart by given degrees
counterclockwise from the x-axis.
• explode is used to set the fraction of radius with which we offset each
wedge.
146 Basic and Advance Phython Programming Language
• autopct is used to format the value of each label. Here, we have set it to
show the percentage value only upto 1 decimal place.
15.9 Histogram
A histogram is graphical display of data using bars of different heights. In a
histogram, each bar groups numbers into ranges. Taller bar shows that more
data falls into that range.
Example
import matplotlib.pyplot as plt
# frequencies
ages = [2,5,70,40,30,45,50,45,43,40,44,
60,7,13,57,18,90,77,32,21,20,40]
# setting the ranges and no. of intervals
range = (0, 100)
bins = 10
# plotting a histogram
plt.hist(ages, bins, range, color = ‘green’,
histtype = ‘bar’, rwidth = 0.8)
# x-axis label
plt.xlabel(‘age’)
# frequency label
plt.ylabel(‘No. of people’)
# plot title
plt.title(‘My histogram’)
# function to show the plot
plt.show()
Output
Data Visualization 147
Note
• Here, we use plt.hist() function to plot a histogram.
• frequencies are passed as the ages list.
• The range could be set by defining a tuple containing min and max
values.
• The next step is to “bin” the range of values—that is, divide the entire
range of values into a series of intervals—and then count how many
values fall into each interval. Here we have defined bins = 10. So, there
are a total of 100/10 = 10 intervals
Output
15.12 Subplot
Subplots are required when we want to show two or more plots in same figure.
We can do it in two ways using two slightly different methods.
Method 1
# importing required modules
import matplotlib.pyplot as plt
import numpy as np
# function to generate coordinates
def create_plot(ptype):
# setting the x-axis values
x = np.arange(-10, 10, 0.01)
# setting the y-axis values
if ptype == ‘linear’:
y=x
elif ptype == ‘quadratic’:
y = x**2
elif ptype == ‘cubic’:
y = x**3
elif ptype == ‘quartic’:
y = x**4
return(x, y)
# setting a style to use
plt.style.use(‘fivethirtyeight’)
# create a figure
fig = plt.figure()
# define subplots and their positions in figure
plt1 = fig.add_subplot(221)
plt2 = fig.add_subplot(222)
plt3 = fig.add_subplot(223)
plt4 = fig.add_subplot(224)
# plotting points on each subplot
x, y = create_plot(‘linear’)
plt1.plot(x, y, color =’r’)
plt1.set_title(‘$y_1 = x$’)
x, y = create_plot(‘quadratic’)
plt2.plot(x, y, color =’b’)
plt2.set_title(‘$y_2 = x^2$’)
x, y = create_plot(‘cubic’)
plt3.plot(x, y, color =’g’)
150 Basic and Advance Phython Programming Language
plt3.set_title(‘$y_3 = x^3$’)
x, y = create_plot(‘quartic’)
plt4.plot(x, y, color =’k’)
plt4.set_title(‘$y_4 = x^4$’)
# adjusting space between subplots
fig.subplots_adjust(hspace=.5,wspace=0.5)
# function to show the plot
plt.show()
output
Method 2
# importing required modules
import matplotlib.pyplot as plt
import numpy as np
# function to generate coordinates
def create_plot(ptype):
# setting the x-axis values
x = np.arange(0, 5, 0.01)
# setting y-axis values
if ptype == ‘sin’:
# a sine wave
y = np.sin(2*np.pi*x)
elif ptype == ‘exp’:
# negative exponential function
y = np.exp(-x)
elif ptype == ‘hybrid’:
Data Visualization 151
Note
• Let us try to understand some important aspects of this code now.
from mpl_toolkits.mplot3d import axes3d
• This is the module required to plot on 3-D space.
ax1 = fig.add_subplot(111, projection=’3d’)
• Here, we create a subplot on our figure and set projection argument as
3d.
ax1.scatter(x, y, z, c = ‘m’, marker = ‘o’)
• Now we use .scatter() function to plot the points in XYZ plane.
• Plotting lines
Example
# importing required modules
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import style
Data Visualization 153
import numpy as np
# setting a custom style to use
style.use(‘ggplot’)
# create a new figure for plotting
fig = plt.figure()
# create a new subplot on our figure
ax1 = fig.add_subplot(111, projection=’3d’)
# defining x, y, z co-ordinates
x = np.random.randint(0, 10, size = 5)
y = np.random.randint(0, 10, size = 5)
z = np.random.randint(0, 10, size = 5)
# plotting the points on subplot
ax1.plot_wireframe(x,y,z)
# setting the labels
ax1.set_xlabel(‘x-axis’)
ax1.set_ylabel(‘y-axis’)
ax1.set_zlabel(‘z-axis’)
plt.show()
Output
Note
• Let us go through important aspects of this program:
x = [1,2,3,4,5,6,7,8,9,10]
y = [4,3,1,6,5,3,7,5,3,7]
154 Basic and Advance Phython Programming Language
z = np.zeros(10)
• Here, we define the base positions of bars. Setting z = 0 means all bars
start from XY plane.
dx = np.ones(10) # length along x-axis
dy = np.ones(10) # length along y-axs
dz = [1,3,4,2,6,7,5,5,10,9] # height of bar
• dx, dy, dz denote the size of bar. Consider he bar as a cuboid, then dx,
dy, dz are its expansions along x, y, z axis respectively.
for h in dz:
. if h > 5:
color.append(‘r’)
else:
color.append(‘b’)
• Here, we set the color for each bar as a list. The color scheme is red for
bars with height greater than 5 and blue otherwise.
ax1.bar3d(x, y, z, dx, dy, dz, color = color)
• Finally, to plot the bars, we use .bar3d() function.
• Plotting curves
Example
# importing required modules
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
# setting a custom style to use
style.use(‘ggplot’)
# create a new figure for plotting
fig = plt.figure()
# create a new subplot on our figure
ax1 = fig.add_subplot(111, projection=’3d’)
# get points for a mesh grid
u, v = np.mgrid[0:2*np.pi:200j, 0:np.pi:100j]
# setting x, y, z co-ordinates
Data Visualization 155
x=np.cos(u)*np.sin(v)
y=np.sin(u)*np.sin(v)
z=np.cos(v)
# plotting the curve
ax1.plot_wireframe(x, y, z, rstride = 5, cstride = 5, linewidth = 1)
plt.show()
Output
Note
• Here, we plotted a sphere as a mesh grid. Let us go through some
important parts:
u, v = np.mgrid[0:2*np.pi:200j, 0:np.pi:100j]
• We use np.mgrid in order to get points so that we can create a mesh.
You can read more about this here.
x=np.cos(u)*np.sin(v)
y=np.sin(u)*np.sin(v)
z=np.cos(v)
• This is nothing but the parametric equation of a sphere.
ax1.plot_wireframe(x, y, z, rstride = 5, cstride = 5, linewidth = 1)
• Agan, we use .plot_wireframe() method. Here, rstride and cstride
arguments can be used to set how much dense our mesh must be.
156 Basic and Advance Phython Programming Language
Note
Everything is pretty much clear in the first example but there is a thing that
needs to be focused on, “Setting size of the canvas”, what this basically means
is to set the size of the figure on which you want to plot the graph, the syntax
is like this.
add_axes([left, bottom, width, height])
Data Visualization 157
The values of left, bottom, height and width lies between 0 to 1. Another
example will make you more clear about this concept.
Example
# importing matplotlib library
import matplotlib.pyplot as plt
# x-axis values
x =[0, 1, 2, 3, 4, 5, 6]
# y-axis values
y =[0, 1, 3, 6, 9, 12, 17]
# creating the canvas
fig = plt.figure()
# setting size of first canvas
axes1 = fig.add_axes([0, 0, 0.7, 1])
# plotting graph of first canvas
axes1.plot(x, y, ‘mo--’)
# setting size of second canvas
axes2 = fig.add_axes([0.1, 0.5, 0.3, 0.3])
# plotting graph of second canvas
axes2.plot(x, y, ‘go--’)
# displaying both graphs
plt.show()
Output
16
Object Oriented Programming in
Python
16.1.2 Abstraction
Abstraction in Python is the process of hiding the real implementation of an
application from the user and emphasizing only on usage of it. For example,
consider you have bought a new electronic gadget. Along with the gadget, you
get a user guide, instructing how to use the application, but this user guide has
no info regarding the internal working of the gadget.
Another example is, when you use TV remote, you do not know how pressing
a key in the remote changes the channel internally on the TV. You just know
that pressing + volume key will increase the volume.
Class classname(object):
def __init__(self): #constructor
self.variable_name=value #attributes
self.variable_name=’value’
def method_name(self):
Body of method
def method_name(self, f1, f2): #f1, f2 are formal argument
Body of method
OR
Class classname:
def __init__(self, f1, f2): #constructor #f1, f2 are formal argument
self.variable_name=value #attributes
self.variable_name=’value’
def method_name(self):
Body of method
def method_name(self, f1, f2): #f1, f2 are formal argument
Body of method
Class: class keyword is used to create a class
Object: object represents the base class name from where all classes in
python are derived. This class is also derived from object class. This is
optional
__init__():This method is use to initialize the variable. This is a special
method. We do not call this method explicitly.
Self: self is a variable which refers to current class instance/object
Example
class computer:
def feature(self): #self as pointer it is take object atumatically
print(“i5,8gb,1tb”)
com1=computer() #object it means taken raw material for making
computer
com2=computer()
computer.feature(com1) #1st method for parameter pass this is given for
final shape for computer
com2.feature() #2nd method for parameter pass
Object: object is class type variable or class instance. To use a class we
should create an object to class
162 Basic and Advance Phython Programming Language
Syntax:
Object_name=class_name()
Object_name=class_name(arg)
Example without argument
Class Mobile:
def_init_(self):
self.model=’RealMe X’
def show_model(self):
print(‘model:’, self.model)
realme=Mobile() #object call
Note:
realme=Mobile()
realme.model # method call
• A block of memory is allocated on heap. The size of allocated memory be
decided from the attributes and method available in the class (Mobile).
• After allocating memory, the special method_init_() is called internally.
This method stores the initial data into the variables.
• The allocated memory location adrdress of the instance is returned into
object(realMe)
• The memory location is passed to self
def show_model(self):
print(‘model:’, self.model)
realme=Mobile(‘RealMe X’) #object call
Type of variable
(i) Instance variable (ii) class variable or static variable
Example Instance variable
class computer:
def __init__(self,ram,hd): #for define instance variable or value define
within function
self.ram=ram
self.hd=hd
def feature(self): #self as pointer it is take object atumatically and this
method instance method
print(“your computer config is:”,self.ram,self.hd)
com1=computer(“8gb”,”1tb”) #object it means taken raw material for
making computer
com2=computer(“16gb”, “2tb”)
164 Basic and Advance Phython Programming Language
computer.feature(com1) #1st method for parameter pass this is given for final
shape for computer
com2.feature() #2nd method for parameter pass
computer.feature(com1) #1st method for parameter pass this is given for final
shape for computer
com2.feature() #2nd method for parameter pass
Note: init function automatically call
Note which method use only instance variable it is called instance method.
This type method not use class variable or static variable
@classmethod
def show_model(cls):
print(“Fingerprint:”,cls.fp) #accessing class variable inside class
method
realme=mobile()
redmi=mobile()
geek=mobile()
print(“RealMe:”, mobile.fp)
print(“Remi:”, mobile.fp)
print(“geek:”, mobile.fp)
print()
mobile.fp=’No’ #change class value out side method
print(“RealMe:”, mobile.fp)
print(“Remi:”, mobile.fp)
print(“geek:”, mobile.fp)
Class Method
class method are the methods which act upon the class variable or ststic
variable of the class.
decorator @classmethod need to write above the class method
By default, the first parameter of class method is cls which refers to the class
itself.
Syntax:
@classmethod
def method_name(cls): # class method without parameter
method body
Example
class mobile:
fp=’yes’
@classmethod
def show_model(cls):
print(“Fingerprint:”,cls.fp)
realme=mobile()
mobile.show_model() #calling class method without argument
calling class method
syntax: classname.method_name()
class method with parameter
@classmethod
def method_name(cls,f1,f2): # class method with parameter
method body
168 Basic and Advance Phython Programming Language
Example
class mobile:
fp=’yes’
@classmethod
def show_model(cls,r):
cls.ram=r
print(“Fingerprint:”,cls.fp)
print(“RAM:”,cls.ram)
realme=mobile() #object
mobile.show_model(‘4GB’) #calling class method without argument
Calling class method
syntax: classname.method_name(actual_argument)
Accessing class/static variable
With class method: To access class variable, we need class methods with cls
as first parameter then we can access class variable using cls.variable_name.
Class mobile:
fp=yes #class variable
realme=mobile()
redmi=mobile()
geek=mobile()
mobile.fp #yes
Object Oriented Programming in Python 169
realme.fp #yes
redmi.fp #yes
geek.fp #yes
Note: if change the any value using class name and class variable then effect
instance object and class namespace both e.g
mobile.fp=no
mobile.fp #no
realme.fp #no
redmi.fp #no
geek.fp #no
but if change using the class variable and instance name then effect only
single object e.g.
realme.fp=not working
mobile.fp #no
realme.fp # not working
redmi.fp #no
geek.fp #no
def_init_(self):
self.model=’RealMe X’ #instance variable
def show_model(self): #instance method
self.model #accessing instance variable inside instance method
realme=Mobile() #object call
realme.show_model() # calling instance method w/o argument
synatax: calling instance method with argument
syntax: object_name.method_name(actual_argument)
Example
Class Mobile:
def_init_(self):
self.model=’RealMe X’ #instance variable
def show_model(self,p): #instance method
self.price=p # instance variable
print(self.model, self.price)
realme=Mobile() #object call
realme.show_model(1000) # calling instance method w/o argument
(i) Accessor methods (ii) mutator methods
Syntax:
@staticmethod
def method_name():
Mehod body
Or
@staticmethod
def method_name(f, f2): #with parameter
Mehod body
Example
class mobile:
@staticmethod #decorator
def show_model(): #static method
print(‘Raelme X’)
realme=mobile()
mobile.show_model() #calling static method without argument
Calling static method with argument
Syntax: classname.method_name(actual parameter)
Example
class mobile:
@classmethod
def show_model(m, p):
model=m
price=p
print(model, price)
realme=mobile()
mobile.show_model(‘RealMe X’,101) #calling static method with argument
Example Class variable or static variable and static method
class computer:
name=”dell” #class variable or static variable
def __init__(self,ram,hd,pro):
self.ram=ram
self.hd=hd
self.pro=”i5”
def feature(self): #self as pointer it is take object atumatically
print(“your computer config is:”,self.ram,self.hd,self.pro)
@classmethod
174 Basic and Advance Phython Programming Language
def company(cls):
print(“company name is:”,cls.name)
@staticmethod #static method
def price():
print(“the price is 45k”)
com1=computer(“8gb”,”1tb”,pro=”i6”) #object it means taken raw
material for making computer
com2=computer(“16gb”, “2tb”,pro=”i5”)
com1.pro=”i6”
computer.feature(com1) #1st method for parameter pass this is given for final
shape for computer
com2.feature() #2nd method for parameter pass
com2.company() #call classmethod
com2.price() #call static method
Note: static method use no variable is call static method, class method use
class variable and instance method use instance variable.
print(“feature2 of a”)
class Mother:
def feature3(self):
print(“feature1 of b”)
def feature4(self):
print(“fature2 of b”)
class Son(Father,Mother):
def feature5(self):
print(“feature1 of c”)
def feature6(self):
print(“fature2 of c”)
ob1=Son()
ob1.feature4()
16.5 Multiple Level Inheritance
In multi-level inheritance, the class inherits the feature of another derived
class (child class)
Example
class a:
def feature1(self):
print(“fature of 1”)
def feature2(self):
print(“feature2 of a”)
class b(a):
def feature3(self):
print(“feature1 of b”)
def feature4(self):
print(“fature2 of b”)
class c(b):
def feature5(self):
print(“feature1 of c”)
def feature6(self):
print(“fature2 of c”)
ob1=c()
ob1.feature1()
Example
class a:
def __init__(self): #constructor method
print(“hii”)
def feature1(self):
print(“fature1 of a”)
def feature2(self):
print(“feature2 of a”)
class c:
def __init__(self): #constructor method
print(“cc”)
def feature1(self):
print(“fature1 of c”)
def feature2(self):
print(“feature2 of c”)
class b(a,c):
def __init__(self): #constructor method
print(“bye”)
super().__init__()
def feature3(self):
print(“feature1 of b”)
def feature4(self):
print(“fature2 of b”)
ob1=b()
output:
hii
bye
Syntax
Class parentclassName(object):
Members of parent class
Class ChildclassName1(ParentClassName):
Members of child class2
Class ChildclassName2(ParentClassName):
Members of child class2
Example
class Father:
def showF(self):
print(“Father class method”)
class Son(Father):
def showS(self):
print(“Son class method”)
class Daughter(Father):
def showD(self):
print(“Daughter class method”)
s=Son()
s.showS()
s.showF() #error
16.8 Polymorphism
If a variable, object or method perform different behaviour according to
situation, it is called polymorphism.
• Duck Typing
• Operator overloading
Object Oriented Programming in Python 181
• Method overloading
• Method overriding
Walk-thapak thapak
Walk-tabdak tabdak
182 Basic and Advance Phython Programming Language
Example
class duck:
def walk(self):
print(“thapak thapak”)
clas horse:
def walk(self):
print(“tabdak tabdak”)
def myfunction(obj):
obj.walk()
d=duck()
myfunction(d)
obj.sum()
obj.sum(10)
output:
2nd sum method
Note: In python overloading is not perform. If above program is run the 2nd
output come and 1st output error show because last function priority is high.
17
Modules in Python Programming
17.1 Modules
• A module is a file containing python definitions and statements.
• A python module is (.py file) containing variables, class definitions,
statement and function related to a particular task. The major feature
of having module is that its content can be reused in other programs,
without having to rewrite or recreate them.
• They are executed only the first time the module name is encounter in an
import statement.
Type of modules:
• User defined modules
• Built-in modules
Ex.-array, math, numpy, sys, etc.
Module 1 Module 2
Display () Display ()
Client
188 Basic and Advance Phython Programming Language
Pack2 folder
import sys
sys.path.append(“C:/Users/AGYA VERMA/PycharmProjects/myProject/
pack1”)
#aproach1
import module1
import module2
module1.display()
module2.show()
#aproach2
from module1 import*
from module2 import*
display()
show()
Example
Import modules from two different packages
Pack 1
Pack 1
Module 1 Module 2
Display () Display ()
Client
import sys
sys.path.append(“C:/Users/AGYA VERMA/PycharmProjects/myProject/
demo1”)
from module1 import*
sys.path.append(“C:/Users/AGYA VERMA/PycharmProjects/myProject/
demo1/demo2”)
from module2 import*
module1.display()
module2.show()
Modules in Python Programming 189
Rules
• PVM can not create objects of an abstract class.
• It is not necessary to declare all methods abstract in a abstract class
• Abstract class can have abstract method and concrete methods
• If there is any abstract method in a class, that class must be abstract.
• The abstract methods of an abstract class must be defined in its child
class/subclass.
• If you are inheriting abstract class that have abstract method, you must
either provide the implementation of the method or make this class
abstract.
When use abstract class
We use abstract class when there are some common feature shared by all the
objects as they are
Modules in Python Programming 191
17.4 Interface
In python, the interface concept is not explicity available, like available in
other language e.g. Java
In python, an interface is an abstract class which contains only abstract
method but not a single concrete method
Example
From abc import ABC, abstractmethod
Class Father(ABC): #abstract class
@abstractmethod
def disp(self): #abstract method
pass
class child(Father):
def disp(self):
print(“child class”)
print(“defing abstract method”)
c=child()
c.disp()
Rules
• All methods of an interface is abstract.
• We can not create object of interface.
• If a class is implementing an interface it has to define all the methods
given in that interface.
• If a class does not implement all the methods declared in the interface,
the class must be declared abstract.
192 Basic and Advance Phython Programming Language
In this chapter, we will learn to make GUIs using Python. We will see different
toolkits that Python provides for GUI programming. Then we will discuss the
Tkinter, one of the most commonly used modules, in detail.
Let us start by seeing different modules Python offers.
Python Libraries for GUI Programming
We can use any of the following toolkits in Python for GUI programming.
1. Tkinter: Tkinter is a standard package used for GUI programming in
Python. This is built on top of the Tk interface.
2. PyQt:PyQt is a Python toolkit binding of the Qt toolkit. Qt is a C++
framework that is used by Python to implement a cross-platform PyQt
toolkit as a plug-in.
3. wxPython: wxPython is also a cross-platform GUI toolkit. It is a wrapper
for the API wxWidgets.
root.geometry(“400x500+300+150”)
root.resizable(0,0)
root.mainloop()
• Rowspan: The height of the widget, i.e. the number of the row up to
which the widget is expanded.
• Sticky: If the cell is larger than a widget, then sticky is used to specify
the position of the widget inside the cell. It may be the concatenation of
the sticky letters representing the position of the widget. It may be N, E,
W, S, NE, NW, NS, EW, ES.
Example
# !/usr/bin/python3
from tkinter import *
parent = Tk()
name = Label(parent,text = “Name”).grid(row = 0, column = 0)
e1 = Entry(parent).grid(row = 0, column = 1)
password = Label(parent,text = “Password”).grid(row = 1, column = 0)
e2 = Entry(parent).grid(row = 1, column = 1)
submit = Button(parent, text = “Submit”).grid(row = 4, column = 0)
parent.mainloop()
Output
Example
from turtle import *
t = Turtle() #object in python
wn=Screen()
206 Basic and Advance Phython Programming Language
output
AssertionError: 5 != 6
Example 2
import unittest
class Testsum(unittest.TestCase):
def testsum1(self):
self.assertEqual(sum([1,2,3]),6)
def testsum2(self):
self.assertEqual(sum([1,2,2]),5)
unittest.main()
output:
No error
20.2.1 Multithreading
Using multiple threads in program or process
Data compression:
with help of zlib.compress(s) and bzz.compress(s) we can get compress the
bytes of string
Syntax: zlib.compress(string), bzz.compress(string)
Example
import zlib
s=”welcome to python”
print(s)
print(len(s)) #output 18
t=zlib.compress(s)
print(t)
print(len(t)) #output 26
import bzz
t=bzz.compress(s)
print(t)
print(len(t)) #output 53
print(os.listdir())
print(os.getcwd())
print(os.getcwdb())
print(os.chdir(‘C:\itutees’))
print(os.getcwd())
os.system(‘mkdir xyz’)
os.renames(‘xyz’,’abc’)
s=”itutees 123”
f=re.findall(“\d”,s)
print(f)
. any character(except newline character)
s=”welcome to itutees”
f=re.findall(“it....s”,s)
print(f)
^ starts with
s=”welcome to itutees”
f=re.findall(“^welcome”,s)
print(f)
$ ends with
s=”welcome to itutees”
f=re.findall(“itutees$”,s)
print(f)
* Zero or more occurences
s=”The ran in spain”
f=re.findall(“ai*”,s)
print(f)
+ Zero or more occurences
s=”welcome to itutees”
f=re.findall(“ai+”,s)
print(f)
{} exactly the specify number of occurance
s=”welcome to itutees”
f=re.findall(“te{2}”,s)
print(f)
: either or
s=’good boy’
f=re.findall(“good|nice”,s)
print(f)
20.5 Datetime Module
• datetime- it handles date and time. It has year, month, day, hour, minute,
second, microsecond and tzinfo attributes
• date-it handle dates of Gregorian clender, without taking time zone into
consideration. It has year month and day attributes.
• Time-it handles time assuming that every day has exactly 24x60x60
seconds. It has hour, minute, second, microsecond and tzinfo attributes.
Brief Tour of the Standard Library 213
Example
from datetime import datetime
ct=datetime.now()
print(ct)
print(ct.year)
output:
2021-12-05 14:18:49.826925
2021
4 log(x[, base])
Returns the Log of x, where base is given. The default base is e
5 log2(x)
Returns the Log of x, where base is 2
6 log10(x)
Returns the Log of x, where base is 10
Example
import math
print(‘The value of 5^8: ‘ + str(math.pow(5, 8)))
print(‘Square root of 400: ‘ + str(math.sqrt(400)))
print(‘The value of 5^e: ‘ + str(math.exp(5)))
print(‘The value of Log(625), base 5: ‘ + str(math.log(625, 5)))
print(‘The value of Log(1024), base 2: ‘ + str(math.log2(1024)))
print(‘The value of Log(1024), base 10: ‘ + str(math.log10(1024)))
output:
The value of 5^8: 390625.0
Square root of 400: 20.0
The value of 5^e: 148.4131591025766
The value of Log(625), base 5: 4.0
The value of Log(1024), base 2: 10.0
The value of Log(1024), base 10: 3.010299956639812
Example
import math
print(‘The value of Sin(60 degree): ‘ + str(math.sin(math.radians(60))))
print(‘The value of cos(pi): ‘ + str(math.cos(math.pi)))
print(‘The value of tan(90 degree): ‘ + str(math.tan(math.pi/2)))
print(‘The angle of sin(0.8660254037844386): ‘ + str(math.degrees(math.
asin(0.8660254037844386))))
output:
The value of Sin(60 degree): 0.8660254037844386
The value of cos(pi): -1.0
The value of tan(90 degree): 1.633123935319537e+16
The angle of sin(0.8660254037844386): 59.99999999999999
ISBN 939138363-7
9 789391 383633