Py-23 02 22
Py-23 02 22
By
N.RAJENDER
• Python is one of the most popular and widely used programming language used for set
of tasks including console based, GUI based, web programming and data analysis.
• Python is a easy to learn and simple programming language so even if you are new to
programming, you can learn python without facing any problems.
• Fact: Python is named after the comedy television show Monty Python's Flying Circus.
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a
functional way.
• Python syntax can be executed by writing directly in the Command Line:
• print("Hello, World!")
• Or by creating a python file on the server, using the .py file extension, and
running
16/04/2025 it in the Command Line
Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 5
Python Applications
• Python is a general-purpose programming language that makes it applicable in almost all domains
of software development. Python as a whole can be used to develop any type of applications.
• Here, we are providing some specific application areas where python can be applied.
• Web Applications
• Desktop GUI Applications
• Software Development
• Scientific and Numeric
• Business Applications
• Console Based Application
• Audio or Video based Applications
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 6
Basics of Python
• Comments in python:
• Comments are non-executable statements in Python. It means neither the python
compiler nor the PVM will execute them. Comments are intended for human
understanding, not for the compiler or PVM. Therefore, they are called non-executable
statements.
• There are two types of commenting features available in Python: These are single-line
comments and multi-line comments.
1.Single Line Comments.
• A single-line comment begins with a hash (#) symbol and is useful in mentioning that
the whole line should be considered as a comment until the end of the line.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 7
• Example:
# This is single line comment.
print("Hello Python").
2. Multi Line Comment
Multi lined comment can be given inside triple quotes. The must start at beginning of the
line.
Example:
'''This
is
Multi line comment'''
print("Hello Python")
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 8
Python Indentation
Creating Variables
Example
x=5
y = "python"
Variables do not need to be declared with any particular type, and can even change type after they have been
set.
Example
x = "Salary"
16/04/2025# x is now of type str Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 11
• Get the Type
You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
type(x)
type(y)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 22
Extending indexing
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and
convenient way to slice a string both syntax wise and execution wise.
Syntax
string[start : end : step]
start, end and step have the same mechanism as slice() constructor.
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands
Operator Description
+ (addition) Add two operands
+= (Assignment after Addition) It adds right operand to the left operand and assign the result to left operand.
-= (Assignment after Subtraction) It subtracts right operand from the left operand and assign the result to left
operand.
*= (Assignment after Multiplication) It multiplies right operand with the left operand and assign the result to left
operand.
/= (Assignment after Division) It divides left operand with the right operand and assign the result to left
operand.
%= (Assignment after Modulus) It takes modulus using two operands and assign the result to left operand.
**= (Assignment after Exponent) Performs exponential (power) calculation on operators and assign value to
the left operand.
//= (Assignment after floor division) It performs floor division on operators and assign value to the left operand.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 29
Identity Operators
• Identity operators are used to compare the objects, not if they are equal,
but if they are actually the same object, with the same memory location.
Operator Description
is Returns true if both variables are the same object ( if id(x) equals id(y) )
is not Returns true if both variables are not the same object
x = 'Hello world'
print('H' in x)
print('hello' not in x)
• provides us with two inbuilt functions to read the input from the keyboard.
input ( prompt )
raw_input ( prompt )
input ( ) : This function first takes the input from the user and then evaluates the
expression, which means Python automatically identifies whether user entered a
string or a number or list. If the input provided is not correct then either syntax error
or exception is raised by python.
Operator
Description
+ It is known as concatenation operator used to concatenate two lists
* It is known as repetition operator. It concatenates the multiple copies of the same list.
[] It is known as slice operator. It is used to access the list item from list.
[:] It is known as range slice operator. It is used to access the range of list items from list.
in It is known as membership operator. It returns if a particular item is present in the
specified list.
not in It is also a membership operator and It returns true if a particular list item is not present in
the list.
Unlike other languages, python provides us the flexibility to use the negative
indexing also. The negative indices are counted from the right. The last
element (right most) of the tuple has the index -1, its adjacent left element is
present at the index -2 and so on until the left most elements is encountered.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 54
Tuple Operators
Operator Description
+ It is known as concatenation operator used to concatenate two tuples
* It is known as repetition operator. It concatenates the multiple copies of the same tuple.
[:] It is known as range slice operator. It is used to access the range of items from tuple.
not in It is also a membership operator and It returns true if a particular item is not present in the
tuple.
Python provides the following built-in functions which can be used with
the tuples.
len()
max()
min()
tuple()
sum()
sorted()
index()
count()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 58
len()
In Python len() is used to find the length of tuple,i.e it returns the number of
items in the tuple.
Syntax:len(tuple)
num=(1,2,3,4,5,6)
print(“length of tuple :”,len(num))
max()
In Python max() is used to find maximum value in the tuple.
Syntax:max(tuple)
num=(1,2,3,4,5,6)
lang=('java','c','python','cpp')
print("Max of tuple :",max(num))
print("Max
16/04/2025 of tuple :",max(lang))
Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 59
min()
In Python min() is used to find minimum value in the tuple.
Syntax:min(tuple)
num=(1,2,3,4,5,6)
lang=('java','c','python','cpp')
print("Min of tuple :",min(num))
print("Min of tuple :",min(lang))
sum()
In python, sum(tuple) function returns sum of all values in the tuple. Tuple
values must in number type.
Syntax:sum(tuple)
num=(1,2,3,4,5,6)
print(“sum
16/04/2025 of tuple items :”,sum(num))
Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 60
sorted()
In python, sorted (tuple) function is used to sort all items of tuple in an
ascending order. It also sorts the items into descending and ascending order. It
takes an optional parameter 'reverse' which sorts the tuple into descending
order.
Syntax: sorted (tuple[,reverse=True])
num=(1,3,2,4,6,5)
lang=('java','c','python','cpp')
print(sorted(num))
print(sorted(lang))
print(sorted(num,reverse=True))
Syntax: if expression:
#block of statements
else:
#another block of statements
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 69
marks = int(input("Enter the marks :"))
if marks > 85 and marks <= 100:
print("Congrats! you scored grade A..")
elif marks > 60 and marks <= 85:
print("You scored grade B + ..")
elif marks > 40 and marks <= 60:
print("You scored grade B ..")
elif (marks > 30 and marks <= 40):
print("You scored grade C ..")
else:
print("Sorry you are fail ?")
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 70
Loop Statements in Python
Sometimes we may need to alter the flow of the program. If the execution of
a specific code may need to be repeated several numbers of times then we
can go for loop statements.
For this purpose, the python provide various types of loops which are capable
of repeating some specific code several numbers of times. Those are,
while loop
for loop
while loop
With the while loop we can execute a set of statements as long as a condition
is true. The while loop is mostly used in the case where the number of
iterations is not known in advance.
The for loop in Python is used to iterate the statements or a part of the
program several times. It is frequently used to traverse the data structures like
list, tuple, or dictionary.
Syntax: for iterating_var in sequence:
statement(s)
Eg:- i=1
n=int(input("Enter n value : "))
for i in range(i,n):
print(i)
Syntax:
for iterating_var1 in sequence:
for iterating_var2 in sequence:
#block of statements
In other words, we can say that break is used to abort the current
execution of the program and the control goes to the next line after the
loop.
Example:
num = 0
print("Odd numbers in between 1 to 10")
while(num < 10):
num = num + 1
if (num % 2) == 0:
continue
print(num)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 84
Set Sequence in Python
In python, the set can be defined as the unordered collection of various items enclosed
within the curly braces. The elements of the set cannot be duplicate. The elements of
the python set must be immutable.
Unlike other collections in python, there is no index attached to the elements of the
set, i.e., we cannot directly access any element of the set by the index. However, we
can print them all together or we can get the list of elements by looping through the
set.
Creating a set
The set can be created by enclosing the comma separated items with the curly braces.
Syntax:
Set={value1, value2….}
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 85
Example:
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday"}
print(Days)
print(type(Days))
print("Looping through the set elements ... ")
for i in Days:
print(i)
Operator Description
| Union Operator
& Intersection Operator
- Difference Operator:
• The union of two sets are calculated by using the or (|) operator. The
union of the two sets contains the all the items that are present in
both the sets.
Example:
Days1={"Mon","Tue","Wed","Sat"}
Days2={"Thr","Fri","Sat","Sun","Mon"}
print(Days1 | Days2)
Example:
Days1={"Mon","Tue","Wed","Sat"}
Days2={"Thr","Fri","Sat","Sun","Mon"}
print(Days1 & Days2)
The difference of two sets can be calculated by using the subtraction (-)
operator. The resulting set will be obtained by removing all the
elements from set 1 that are present in set 2.
Example:
Days1={"Mon","Tue","Wed","Sat"}
Days2={"Thr","Fri","Sat","Sun","Mon"}
print(Days1 - Days2)
• len(set)
• max(set)
• min(set)
• sum(set)
• sorted(set)
• set()
• add()
• update()
• discard()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 91
• remove()
• pop()
• clear()
• union()
• intersection()
• difference()
• issubset()
• issuperset()
Syntax: max(set)
Example:
num={1,2,3,4,5,6}
lang={'java','c','python','cpp'}
print("Max of set :",max(num))
print("Max of set :",max(lang))
Syntax:sum(set)
Example:
num={1,2,3,4,5,6}
print(“sum of set items :”,sum(num))
Syntax:
sorted (set[,reverse=True])
Example:
num={1,3,2,4,6,5}
lang={'java','c','python','cpp'}
print(sorted(num))
print(sorted(lang))
print(sorted(num,reverse=True))
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 97
set()
The set() method takes sequence types and converts them to sets. This is used to convert a given string
or list or tuple into set.
Syntax:
set(sequence)
Example:
set1=set("PYTHON")
print(set1)
days=["Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun"]
set2 = set(days)
print(set2)
days=("Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun")
set3 = set(days)
print(set3)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 98
add()
In python, the add() method used to add some particular item to the set.
Syntax:set.add (item)
Example:
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
print("\n printing the original set ... ")
print(Days)
Days.add("Saturday");
Days.add("Sunday");
print("\n Printing the modified set...");
print(Days)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 99
update()
Python provides the update () method to add more than one item in
the set.
Syntax:set.update ([item1, item2…])
Example:
Months={"Jan","Feb","Mar","Apr"}
print("\n Printing the original set ... ")
print(Months)
Months.update (["May","Jun","Jul"])
print("\n Printing the modified set...");
print(Months)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 100
discard()
Python provides discard () method which can be used to remove the items from the set. If item
doesn't exist in the set, the python will not give the error. The program maintains its control flow.
Syntax:set.discard (item)
Example:
Months={"Jan","Feb","Mar","Apr"}
print("\n printing the original set ... ")
print(Months)
Months.discard("Apr")
print("\n Printing the modified set...");
print(Months)
Months.discard("May") #doesn’t give error
print("\n Printing the modified set...");
print(Months)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 101
remove()
Python provides remove () method which can be used to remove the items from the set. If item
doesn't exist in the set, the python will give the error.
Syntax:set.remove (item)
Example:
Months={"Jan","Feb","Mar","Apr"}
print("\n printing the original set ... ")
print(Months)
Months.remove("Apr")
print("\n Printing the modified set...");
print(Months)
Months.remove("May") #it give error
print("\n Printing the modified set...");
print(Months)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 102
pop()
In Python, pop () method is used to remove the item. However, this method will
always remove the last item.
Syntax:set.pop ()
Example:
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
print("\n printing the original set ... ")
print(Days)
Days.pop()
print("\n Printing the modified set...");
print(Days)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 103
clear()
In Python, clear () method is used to remove the all items in set.
Syntax:set.clear ()
Example:
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
print("\n printing the original set ... ")
print(Days)
Days.clear()
print("\n Printing the modified set...");
print(Days)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 104
union ()
In Python, the union () method is used to perform union of two sets.
The union of the two sets contains the all the items that are present in
both the sets.
Syntax:set1.union (set2)
Example:
Days1={"Mon","Tue","Wed","Sat"}
Days2={"Thr","Fri","Sat","Sun","Mon"}
print(Days1.union(Days2))
Syntax:set1.intersection (set2)
Example:
Days1={"Mon","Tue","Wed","Sat"}
Days2={"Thr","Fri","Sat","Sun","Mon"}
print(Days1.intersection(Days2))
Syntax:set1.difference (set2)
Example:
Days1={"Mon","Tue","Wed","Sat"}
Days2={"Thr","Fri","Sat","Sun","Mon"}
print(Days1.difference(Days2))
Syntax:set1.issubset (set2)
Example:
set1={1,2,3,4}
set2={1,2,3,4,5,6,7,8,9}
print(set1.issubset(set2))
print(set2.issubset(set1))
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 108
issuperset()
The issuperset () method returns True if a set has every elements of
another set (passed as an argument). If not, it returns False.
Syntax:set1.issuperset (set2)
Example:
set1={1,2,3,4}
set2={1,2,3,4,5,6,7,8,9}
print(set1.issuperset(set2))
print(set2.issuperset(set1))
• The dictionary can be created by using multiple key-value pairs which are separated by
comma(,) and enclosed within the curly braces {}.
• Example:
• student = {"Name": "abc", "Age": 21, "Rollno":56,"Branch":“IT"}
• print(student)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 110
Accessing the dictionary values
The data can be accessed in the list and tuple by using the indexing.
However, the values can be accessed in the dictionary by using the keys
as keys are unique in the dictionary.
Example:
student = {"Name": “abc", "Age": 21, "Rollno":56,"Branch":“IT"}
print("Name : ",student["Name"])
print("Age : ",student["Age"])
print("RollNo : ",student["Regno"])
print("Branch : ",student["Branch"])
Example:
student = {"Name": “abc", "Age": 22, "Rollno":56,"Branch":“IT"}
print("printing student data .... ")
print(student)
student["Name"]=“xyz"
print("printing updated data .... ")
print(student)
Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
print("printing student data .... ")
print(student)
del student["Branch"]
print("printing the modified information ")
print(student)
Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
print("Keys are :")
for x in student:
print(x)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 114
print all the values of a dictionary
Example:
print("values are :")
for x in student:
print(student[x])
Example:
print("Key and values are :")
for x,y in student.items():
print(x,y)
len()
copy()
get()
keys()
items()
values()
update()
pop()
clear()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 117
len()
In python, len() function is used to find length of given dictionary.
Syntax:len(dictionary)
Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
print("Length of Dictionary is:",len(student))
Syntax:dictionary.copy()
Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
student2=student.copy()
print(student2)
Syntax:dictionary.get()
Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
print("Name is :",student.get("Name"))
print("RegNo is :",student.get("Regno"))
Syntax:dictionary.keys()
Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
for x in student.keys():
print(x)
Syntax:dictionary.items()
Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
for x in student.items():
print(x)
Syntax:Dictionary.values()
Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
for x in student.values():
print(x)
Syntax:Dictionary.update({key:value,….})
Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
student.update({"Regno":590})
student.update({"phno":56895})
print(student)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 124
• pop()
• In python pop() method removes an element from the dictionary. It removes the
element which is associated to the specified key.
• If specified key is present in the dictionary, it remove and return its value.
• If the specified key is not present, it throws an error KeyError.
• Syntax: Dictionary.pop(key)
• Example:
• student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
• student.pop('Age')
• print(student)
• student.pop('hallno')
• print(student)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 125
clear()
In python, clear() is used to delete all the items of the dictionary.
Syntax:Dictionary.clear()
Example:
student = {"Name": "Kiran", "Age": 22, "Regno":562,"Branch":"CSE"}
print(student)
student.clear()
print(student)
Python provide us various inbuilt functions like range() or print(). Although, the
user can able to create functions which can be called user-defined functions.
Creating Function
In python, a function can be created by using def keyword.
Example:
def sample(): #function definition
print ("Hello world")
Example:
def welcome(name):
print("function with one parameter")
print("welcome : ",name)
welcome("Guest")
• In Python we have lists that serve the purpose of arrays, but they are slow to process.
• NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
• The array object in NumPy is called ndarray, it provides a lot of supporting functions
that make working with ndarray very easy.
• Arrays are very frequently used in data science, where speed and resources are very
important.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 134
Why is NumPy Faster Than Lists?
• NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.
• This behavior is called locality of reference in computer science.
• This is the main reason why NumPy is faster than lists. Also it is optimized to
work with latest CPU architectures.
Import NumPy
• Once NumPy is installed, import it in your applications by adding the import
keyword:
• import numpy
• Now NumPy is imported and ready to use.
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
• Example
#Create a 0-D array with value 1220
import numpy as np
arr = np.array(1220)
print(arr)
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Example
#Create a 3-D array with two 2-D arrays, both containing two arrays with the
values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 141
Access Array Elements
To access elements from 2-D arrays we can use comma separated integers
representing the dimension and the index of the element.
Think of 2-D arrays like a table with rows and columns, where the row
represents the dimension and the index represents the column.
Example
Access the element on the first row, second column
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st row: ', arr[0, 1])
Example
• Slice elements from index 1 to index 5 from the following array:
• import numpy as np
print(arr[1:5]
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 144
Example
#Slice elements from index 4 to the end of the array:
• import numpy as np
print(arr[4:])
Example
#Slice elements from the beginning to index 4 (not included):
• import numpy as np
print(arr[:4]
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 145
Negative Slicing
Use the minus operator to refer to an index from the end:
Example
#Slice from the index 3 from the end to index 1 from the end:
import numpy as np
print(arr[-3:-1])
print(arr[1, 1:4])
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 1:4])
import numpy as np
Example
Make a copy, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy()
arr[0] = 42
print(arr)
print(x)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 156
VIEW:
Example
Make a view, change the original array, and display both arrays:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view()
arr[0] = 42
print(arr)
print(x)
for x in arr:
print(x)
import numpy as np
print(arr)
Searching Arrays
You can search an array for a certain value, and return the indexes that get a
match.
To search an array, use the where() method.
Example
Find the indexes where the value is 4:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 4)
print(x)
x = np.where(arr%2 == 1)
print(x)
Example
Sort a 2-D array:
import numpy as np
print(np.sort(arr))
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 168
Pandas
Functions Description
Pandas Series.map() Map the values from two series that have a common
column.
Pandas Series.std() Calculate the standard deviation of the given set of
numbers, DataFrame, column, and rows.
1.import pandas as pd
2.import numpy as np
3.a = pd.Series(['Java', 'C', 'C++', np.nan])
4.a.map({'Java': 'Core'})
1.import pandas as pd
2.import numpy as np
3.a = pd.Series(['Java', 'C', 'C++', np.nan])
4.a.map({'Java': 'Core'})
5.a.map('I like {}'.format, na_action='ignore')
• 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:
DWDMMarks = {
"Minor-1": [10, 9, 8],
"MSE-1": [26, 25, 24]
}
df = pd.DataFrame(DWDMMarks)
print(df)
DWDMMarks = {
"Minor-1": [10, 9, 8],
"MSE-1": [36, 35, 34]
}
print(df)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 193
Create a DataFrame using List
Example:3
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df =pd.DataFrame(data,columns=['Name','Age'],dtype=float)
Print(df)
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 195
Create a DataFrame from List of Dicts
• List of Dictionaries can be passed as input data to create a DataFrame. The
dictionary keys are by default taken as column names.
Example 1
The following example shows how to create a DataFrame by passing a list of
dictionaries.
import pandas as pd
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data)
print (df)
import pandas as pd
df = pd.read_excel('MyExcel.xlsx')
print(df)
import pandas as pd
df = pd.read_excel('MyExcel.xlsx', sheet_name=1)
print(df)
require_cols = [0,3]
print(required_df)
Remove Rows
One way to deal with empty cells is to remove rows that
contain empty cells.
import pandas as pd
df = pd.read_excel('MyExcel.xlsx')
new_df = df.dropna()
print(new_df.to_string())
Note: By default, the dropna() method returns a new DataFrame, and will not change the original.
import pandas as pd
df = pd.read_excel('MyExcel.xlsx')
new_df = df.dropna()
print(new_df.to_string())
import pandas as pd
df = pd.read_excel('MyExcel.xlsx')
df["Rollno"].fillna(9999)
df["ROLLNO"].fillna(x)
Example
Draw two points in the diagram, one at position (1, 3) and one in 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, 'o')
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 208
Example
Draw a line in a diagram from position (1, 3) to (2, 8) then to (6,
1) and finally to position (8, 10):
Default X-Points
If we do not specify the points in the x-axis, they will get the default values 0, 1,
2, 3, etc. depending on the length of the y-points.
Markers
You can use the keyword argument marker to emphasize each point with a
specified marker:
Line Reference
Line Syntax Description
'-’ Solid line
':’ Dotted line
'--’ Dashed line
'-.’ Dashed/dotted line
Style Or
'solid' (default) '-'
'dotted’ ':'
'dashed’ '--'
'dashdot’ '-.'
'None’ '' or ' '
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 222
The subplot() Function
The subplot() function takes three arguments that describes the layout of the
figure.
The layout is organized in rows and columns, which are represented by the
first and second argument.
The third argument represents the index of the current plot.
plt.subplot(1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is the first plot.
plt.subplot(1, 2, 2)
#the figure has 1 row, 2 columns, and this plot is the second plot.
Note:-You can draw as many plots you like on one figure, just describe the
number of rows, columns, and the index of the plot.
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 223
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 1, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 1, 2)
plt.plot(x,y)
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 224
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 1)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 2)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 3)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 4)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 5)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 6)
plt.plot(x,y)
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 225
Title
You can add a title to each plot with the title() function:
plt.title("SALES").
Super Title
You can add a title to the entire figure with the suptitle() function:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 227
Color Each Dot
You can even set a specific color for each dot by using an array of colors as value for the c argument:
Note: You cannot use the color argument for this, only the c argument.
Example
Set your own color of the markers:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors =
np.array(["red","green","blue","yellow","pink","black","orange","purple","beige","brown","gray","cyan","magenta"])
plt.scatter(x, y, c=colors)
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 228
Matplotlib Bars
Creating Bars
With Pyplot, we can use the bar() function to draw bar graphs:
Example
Draw 4 bars:
Example
Draw 4 horizontal bars:
plt.barh(x, y)
plt.show()
16/04/2025 Mr.N.Rajender,Asst.Prof,Dept of IT,KITSW 231
Bar Color
The bar() and barh() takes the keyword argument
color to set the color of the bars:
Example
A simple pie chart:
Categorical features can only take on a limited, and usually fixed, number of
possible values. For example, if a dataset is about information related to
users, then you will typically find features like country, gender, age group,
etc. Alternatively, if the data you're working with is related to products, you
will find features like product type, manufacturer, seller and so on.
These are all categorical features in your dataset. These features are
typically stored as text values which represent various traits of the
observations. For example, gender is described as Male (M) or Female (F),
product type could be described as electronics, apparels, food etc.