Python Programs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Program - 1: Write a python to create a panda’s series from a dictionary of values and

an ndarray.

Source Code:
import pandas as pd
import numpy as np
d1={'Name':'Sai','RollNo':100,'Marks':75}
s1=pd.Series(d1)
print('Series object from Dictionary Values:')
print(s1)
ndarr=np.arange(10,15)
s2=pd.Series(ndarr)
print('Series object from nd Array Values:')
print(s2)

Output:
Series object from Dictionary Values:
Name Sai
RollNo 100
Marks 75
dtype: object
Series object from nd Array Values:
0 10
1 11
2 12
3 13
4 14
dtype: int32

Result: Thus, the program for a pandas series from a dictionary of values and an
ndarray has been created and executed successfully.

Class 12 – IP – Lab Programs 1


Program - 2: Write a Pandas program to compare the elements of the two Pandas
Series.

Source Code:
import pandas as pd
s1= pd.Series([2,4,6,8,10])
s2= pd.Series([1,3,5,7,10])
print("Series1:")
print(s1)
print("Series2:")
print(s2)
print("Compare the elements of the said Series:")
print("Equals:")
print(s1[s1 == s2])
print("Greater than:")
print(s1[s1 > s2])
print("Less than:")
print(s2[s2 < s1])

Output:
Series1:
0 2
1 4
2 6
3 8
4 10
dtype: int64
Series2:
0 1
1 3
2 5
3 7
4 10
dtype: int64
Compare the elements of the said Series:
Equals:
4 10
dtype: int64
Greater than:
0 2
1 4
2 6
3 8
dtype: int64
Class 12 – IP – Lab Programs 2
Less than:
0 1
1 3
2 5
3 7
dtype: int64

Result: Thus, the program to compare the elements of the two Pandas Series has been
created and executed successfully.

Class 12 – IP – Lab Programs 3


Program - 3: Write a Pandas program to add, subtract, multiple and divide two Pandas
Series.

Source Code:
import pandas as pd
ds1 = pd.Series([2,4, 6, 8,10])
ds2= pd.Series([1,3,5,7,9])
ds = ds1 + ds2
print("Add two Series:")
print(ds)
print("Subtract two Series:")
ds= ds1 - ds2
print(ds)
print("Multiply two Series:")
ds= ds1 * ds2
print(ds)
print("Divide Series1 by Series2:")
ds= ds1 / ds2
print(ds)

Output:
Add two Series:
0 3
1 7
2 11
3 15
4 19
dtype: int64
Subtract two Series:
0 1
1 1
2 1
3 1
4 1
dtype: int64
Multiply two Series:
0 2
1 12
2 30
3 56
4 90
dtype: int64

Class 12 – IP – Lab Programs 4


Divide Series1 by Series2:
0 2.000000
1 1.333333
2 1.200000
3 1.142857
4 1.111111
dtype: float64

Result: Thus, the program to add, subtract, multiple and divide two Pandas Series has
been created and executed successfully.

Class 12 – IP – Lab Programs 5


Program - 4: Write a program to create dataframe for 3 students including name and
roll numbers and add new columns for 5 subjects and 1 column to calculate percentage.
It should include random numbers in marks of all subjects.

Source Code:
import pandas as pd
import numpy as np
import random
D={'Roll':[1,2,3],'Name':['Sai','Maniteja','Neeraj']}
P=[ ]
C=[ ]
M=[ ]
E=[ ]
IP=[ ]
SD=pd.DataFrame(D)
for i in range(3):
P.append(random.randint(25,101))
C.append(random.randint(25,101))
M.append(random.randint(25,101))
E.append(random.randint(25,101))
IP.append(random.randint(25,101))
SD['Phy']=P
SD['Chem']=C
SD['Maths']=M
SD['Eng']=E
SD['IP']=IP
SD['Total']=SD.Phy+SD.Chem+SD.Maths+SD.Eng+SD.IP
SD['Per']=SD.Total/5
print(SD)

Output:
Roll Name Phy Chem Maths Eng IP Total Per
0 1 Sai 80 75 37 38 59 289 57.8
1 2 Maniteja 95 99 60 94 54 402 80.4
2 3 Neeraj 36 26 47 30 36 175 35.0

Result: Thus, the program to create dataframe for 3 students including name and roll
numbers and add new columns for 5 subjects and 1 column to calculate percentage. It
should include random numbers in marks of all subjects has been created and executed
successfully.

Class 12 – IP – Lab Programs 6


Program - 5: Write a python program to convert third column of a DataFrame as
Series object.

Source Code:
import pandas as pd
import numpy as np
d={'Name':['Sai','Neeraj','Maniteja','Bindhu','Saanvi'],'RollNo':[100,101,103,104,105],
'Marks':[65,75,60,85,90]}
df1=pd.DataFrame(d)
print("DataFrame Original Data:")
print(df1)
s1=df1.iloc[:,2]
print("Third column of DataFrame as Series Object:")
print(s1)

Output:
DataFrame Original Data:
Name RollNo Marks
0 Sai 100 65
1 Neeraj 101 75
2 Maniteja 103 60
3 Bindhu 104 85
4 Saanvi 105 90
Third column of DataFrame as Series Object:
0 65
1 75
2 60
3 85
4 90
Name: Marks, dtype: int64

Result: Thus, the program to convert third column of a DataFrame as Series object has
been created and executed successfully.

Class 12 – IP – Lab Programs 7


Program - 6: Write a python program to find marks of all the students greater than 57
and also display whose marks are in between 70 and 80.

Source Code:
import pandas as pd
import numpy as np
d={'Name':['Sai','Sita','Rama','Neeraj','Surya','Saanvi'],
'RollNo':[100,101,102,103,104,105],'Marks':[60,55,75,70,90,85]}
df1=pd.DataFrame(d)
print('DataFrame Object Data:')
print(df1)
while(1):
print('1. Marks Greater Than Some Value:')
print('2. Marks Based on Range:')
print('3. Exit')
ch=int(input('Enter Your Choice:'))
if(ch==1):
n=int(input('Enter Marks to apply on condition:'))
m=df1.iloc[:,2]
print("Marks Greater Than: ",n)
print(m[m>n])
elif(ch==2):
lb=int(input('Enter Lower Bound in a Range:'))
ub=int(input('Enter Upper Bound in a Range:'))
print('Marks Between:',lb,'To',ub)
print(m[(m>=lb)&(m<=ub)])
else:
print('Please Enter Valid Number as a Choice:')
break

Output:
DataFrame Object Data:
Name RollNo Marks
0 Sai 100 60
1 Sita 101 55
2 Rama 102 75
3 Neeraj 103 70
4 Surya 104 90
5 Saanvi 105 85
1. Marks Greater Than Some Value:
2. Marks Based on Range:
3. Exit

Class 12 – IP – Lab Programs 8


Enter Your Choice:1
Enter Marks to apply on condition:70
Marks Greater Than: 70
2 75
4 90
5 85
Name: Marks, dtype: int64
1. Marks Greater Than Some Value:
2. Marks Based on Range:
3. Exit
Enter Your Choice:2
Enter Lower Bound in a Range:60
Enter Upper Bound in a Range:90
Marks Between: 60 To 90
0 60
2 75
3 70
4 90
5 85
Name: Marks, dtype: int64
1. Marks Greater Than Some Value:
2. Marks Based on Range:
3. Exit
Enter Your Choice:3

Result: Thus, the program to find marks of all the students greater than 57 and also
display whose marks are in between 70 and 80 has been created and executed
successfully.

Class 12 – IP – Lab Programs 9


Program - 7: Write a Python Program to create a Series object using arrange ( )
method and perform attributes of Series on it.

Source Code:
import pandas as pd
import numpy as np
obj1=pd.Series(np.arange(10,16),name='Array Range Method')
print('Series Object Original Data:')
print(obj1)
print('Name of Series:',obj1.name)
print('Indexes of Series:',obj1.index)
print('Sizeof Series:',obj1.size)
print('Number of Dimensions of Series:',obj1.ndim)
print('Shape of Series:',obj1.shape)
print('Number of bytes occupied by Series:',obj1.nbytes)
print('Is Series object empty:',obj1.empty)

Output:
Series Object Original Data:
0 10
1 11
2 12
3 13
4 14
5 15
Name: Array Range Method, dtype: int32
Name of Series: Array Range Method
Indexes of Series: RangeIndex(start=0, stop=6, step=1)
Sizeof Series: 6
Number of Dimensions of Series: 1
Shape of Series: (6,)
Number of bytes occupied by Series: 24
Is Series object empty: False

Result: Thus, the program to create a Series object using arrange ( ) method and
perform attributes of Series on it has been created and executed successfully.

Class 12 – IP – Lab Programs 10


Program - 8: Write a Python Program to create a DataFrame using dictionary of
Series, dictionary of Lists.

Source Code:
import pandas as pd
while(1):
print("Create a DataFrame:")
print("1. Using Dictionary of Series:")
print("2. Using Dictionary of Lists:")
print("3.Exit")
choice=int(input("Enter the choice:"))
if(choice==1):
d={'Name':pd.Series(['Sai','Riya','Anu','Surya','Neeraj']),
'RollNo':pd.Series([1,2,3,4,5]),
'Marks':pd.Series([75,80.23,90,92.35,95.50]),
'Address':pd.Series(['Tirupati','Nellore','Kadapa','Kurnool','Chittoor'])}
df1=pd.DataFrame(d)
print("DataFrame Created Using Dictionary of Series:")
print(df1)
elif(choice==2):
d={'Name':pd.Series(['Sai','Riya','Anu','Surya','Neeraj']),
'RollNo':pd.Series([1,2,3,4,5]),
'Marks':pd.Series([75,80.23,90,92.35,95.50]),
'Address':pd.Series(['Tirupati','Nellore','Kadapa','Kurnool','Chittoor'])}
df1=pd.DataFrame(d)
print("DataFrame Created Using Dictionary of Lists:")
print(df1)
elif(choice==3):
break
else:
print("Wrong input,Please enter the numbers between(1-3):")
Output:
Create a DataFrame:
1. Using Dictionary of Series:
2. Using Dictionary of Lists:
3.Exit
Enter the choice:1
DataFrame Created Using Dictionary of Series:
Name RollNo Marks Address
0 Sai 1 75.00 Tirupati
1 Riya 2 80.23 Nellore
2 Anu 3 90.00 Kadapa
3 Surya 4 92.35 Kurnool
Class 12 – IP – Lab Programs 11
4 Neeraj 5 95.50 Chittoor
Create a DataFrame:
1. Using Dictionary of Series:
2. Using Dictionary of Lists:
3.Exit
Enter the choice:2
DataFrame Created Using Dictionary of Lists:
Name RollNo Marks Address
0 Sai 1 75.00 Tirupati
1 Riya 2 80.23 Nellore
2 Anu 3 90.00 Kadapa
3 Surya 4 92.35 Kurnool
4 Neeraj 5 95.50 Chittoor
Create a DataFrame:
1. Using Dictionary of Series:
2. Using Dictionary of Lists:
3.Exit
Enter the choice:3

Result: Thus, the program to create a DataFrame using dictionary of Series, dictionary
of Lists has been created and executed successfully.

Class 12 – IP – Lab Programs 12


Program - 9: Write a Python Program to create a DataFrame object using array ( )
method and perform attributes of DataFrame on it.

Source Code:
import pandas as pd
import numpy as np
arr1=np.array([[1,2,3],[4,5,6],[7,8,9]])
obj1=pd.DataFrame(arr1,columns=['A','B','C'])
print("DataFrame Object Original Data:")
print(obj1)
print('Indexes of DataFrame:',obj1.index)
print('Sizeof DataFrame:',obj1.size)
print('Number of Dimensions of DataFrame:',obj1.ndim)
print('Shape of DataFrame:',obj1.shape)
print('Number of bytes occupied by DataFrame:',obj1.columns)
print('Is DataFrame object an empty:',obj1.empty)
print('Transpose of DataFrame object :\n',obj1.T)

Output:
DataFrame Object Original Data:
A B C
0 1 2 3
1 4 5 6
2 7 8 9
Indexes of DataFrame: RangeIndex(start=0, stop=3, step=1)
Sizeof DataFrame: 9
Number of Dimensions of DataFrame: 2
Shape of DataFrame: (3, 3)
Number of bytes occupied by DataFrame: Index(['A', 'B', 'C'], dtype='object')
Is DataFrame object an empty: False
Transpose of DataFrame object :
0 1 2
A 1 4 7
B 2 5 8
C 3 6 9

Result: Thus, the program to create a DataFrame object using array ( ) method and
perform attributes of DataFrame on it has been created and executed successfully.

Class 12 – IP – Lab Programs 13


Program - 10: Given a Series, print all the elements that are above the 75th percentile.

Source Code:
import pandas as pd
import numpy as np
s=pd.Series(np.array([1,3,4,7,8,8,9]))
print("Pandas Series creating from ndarray:")
print(s)
res=s.quantile(q=0.75)
print()
print("75th percentile of the pandas series is:")
print(res)
print()
print("The elements that are above the 75th percentile:")
print(s[s>res])

Output:
Pandas Series creating from ndarray:
0 1
1 3
2 4
3 7
4 8
5 8
6 9 dtype: int32
75th percentile of the pandas series is:
8.0

The elements that are above the 75th percentile:


6 9

Result: Thus, the program given a Series, print all the elements that are above the 75th
percentile has been created and executed successfully.

Class 12 – IP – Lab Programs 14


Program - 11: Create Data Frame quarterly sales where each row contains the item
category, item name, and expenditure. Group the rows by the category and print the
total expenditure per category.

Source Code:
import pandas as pd
dic={'itemcat':['Car','AC','Aircoller','Washing Machine','Car'],
'itemname':['Ford','Hitachi','Symphony','LG','Tayota'],
'expenditure':[7000000,50000,15000,20000,1200000]}
quartersales=pd.DataFrame(dic)
print("Quarter Sales:")
print(quartersales)
qs=quartersales.groupby('itemcat')
print("Result after Filtering DataFrame:")
print(qs['itemcat','expenditure'].sum())

Output:
Quarter Sales:
itemcat itemname expenditure
0 Car Ford 7000000
1 AC Hitachi 50000
2 Aircoller Symphony 15000
3 Washing Machine LG 20000
4 Car Tayota 1200000
Result after Filtering DataFrame:
itemcat expenditure
AC 50000
Aircoller 15000
Car 8200000
Washing Machine 20000

Result: Thus, the program for Data Frame quarterly sales where each row contains the
item category, item name, and expenditure. Group the rows by the category and print
the total expenditure per category has been created and executed successfully.

Class 12 – IP – Lab Programs 15


Program - 12: Create a data frame for examination result and display row labels,
column labels data types of each column and the dimensions.

Source Code:
import pandas as pd
dict={'Class':['I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'],
'Pass-Percentage':[100,100,100,100,100,100,100,100,100,98.65,100,99.50]}
result=pd.DataFrame(dict,index=['Grade 1','Grade 2','Grade 3','Grade 4','Grade
5','Grade 6',
'Grade 7','Grade 8','Grade 9','Grade 10','Grade 11','Grade 12'])
print("DataFrame Data:")
print(result)
print("Row Lables:")
print(result.index)
print("Column Lables:")
print(result.columns)
print("DataFrame Data Type:")
print(result.dtypes)
print("Shape of the Dataframe is:")
print(result.shape)
print("DataFrame Dimensions:")
print(result.ndim)

Output:
DataFrame Data:
Class Pass-Percentage
Grade 1 I 100.00
Grade 2 II 100.00
Grade 3 III 100.00
Grade 4 IV 100.00
Grade 5 V 100.00
Grade 6 VI 100.00
Grade 7 VII 100.00
Grade 8 VIII 100.00
Grade 9 IX 100.00
Grade 10 X 98.65
Grade 11 XI 100.00
Grade 12 XII 99.50

Class 12 – IP – Lab Programs 16


Row Lables:
Index(['Grade 1', 'Grade 2', 'Grade 3', 'Grade 4', 'Grade 5', 'Grade 6',
'Grade 7', 'Grade 8', 'Grade 9', 'Grade 10', 'Grade 11', 'Grade 12'],
dtype='object')
Column Lables: Index(['Class', 'Pass-Percentage'], dtype='object')
DataFrame Data Type:
Class object
Pass-Percentage float64 dtype: object
Shape of the Dataframe is: (12, 2)
DataFrame Dimensions: 2

Result: Thus, the program a data frame for examination result and display row labels,
column labels data types of each column and the dimensions has been created and
executed successfully.

Class 12 – IP – Lab Programs 17


Program - 13: Filter out rows based on different criteria such as duplicate rows.

Source Code:
import pandas as pd
dict={'Name':['Sai','Maniteja','Neeraj','Indhu','Bhuvana','Neeraj','Sai'],
'MarksinIP':[85,45,92,86,94,92,85]}
marks=pd.DataFrame(dict)
#Find duplicate rows
duplicateRow=marks[marks.duplicated(keep=False)]
print("Duplicate Rows in DataFrame:")
print(duplicateRow)

Output:
Duplicate Rows in DataFrame:
Name MarksinIP
0 Sai 85
2 Neeraj 92
5 Neeraj 92
6 Sai 85

Result: Thus, the program filter out rows based on different criteria such as duplicate
rows has been created and executed successfully.

Class 12 – IP – Lab Programs 18


Program - 14: Importing and exporting data between pandas and CSV file.

Source Code:
import pandas as pd
df=pd.read_csv("D:\IP\Practical\emp.csv")
print("Importing Data From CSV File:")
print(df)
CSV File: Open notepad and copy paste the following data and save it file as
emp.csv
empid,empname,doj
1001,Sai,11-04-1992
1002,Neeraj,13-12-2000
1003,Maniteja,11-03-1998
1004,Saanvi,13-05-1996
1005,Bhuvana,09-04-1994
1006,NaN,NaN

Output:
Importing Data From CSV File:
empid empname doj
0 1001 Sai 11-04-1992
1 1002 Neeraj 13-12-2000
2 1003 Maniteja 11-03-1998
3 1004 Saanvi 13-05-1996
4 1005 Bhuvana 09-04-1994
5 1006 NaN NaN

Class 12 – IP – Lab Programs 19


Source Code:
import pandas as pd
l=[{'Name':'Sai','SirName':'Basineni'},
{'Name':'Maniteja','SirName':'Peta'},
{'Name':'Saanvii','SirName':'Pokala'},
{'Name':'Neeraj','SirName':'Peta'}
]
df1=pd.DataFrame(l)
df1.to_csv('D:\IP\Practical\emp1.csv')
print("Exporting DataFrame Data into CSV file:")

Output:
, Name, SirName
0, Sai, Basineni
1, Maniteja, Peta
2, Saanvii, Pokala
3, Neeraj, Peta

Result: Thus, the program importing and exporting data between pandas and CSV file
has been created and executed successfully.

Class 12 – IP – Lab Programs 20


Program – 15: Draw two line graph where the x axis shows the individual classes and
the y axis shows the number of students participating in ART/COMPUTER inter house
event.

Source Code:
import matplotlib.pyplot as plt
x=[4,5,6,7]
y=[6,10,14,13]
z=[10,12,18,20]
plt.plot(x,y,'g',linestyle="--", linewidth=10)
plt.plot(x,z,'m',linestyle="dotted")
plt.legend(('ART','COMP'),loc='upper left')
plt.title(" ART/COMPUTER Interhouse Competition")
plt.xlabel("CLASS", fontsize="14",color="red")
plt.ylabel("NO OF STUDENTS PARTICIPATING", fontsize="14",
color="blue")
plt.grid(True)
plt.show( )

Output:

Result: Thus, the program to draw two line graph where the x axis shows the
individual classes and the y axis shows the number of students participating in
ART/COMPUTER inter house event has been created and executed successfully.

Class 12 – IP – Lab Programs 21


Program - 16: Given the school result data, analyses the performance of the students
on different parameters, e.g subject wise or class wise.

Source Code:
import matplotlib.pyplot as plt
Subject=['Physics','Chemistry','Hindi','Biology','IP']
Percentage=[85,78,65,90,100]
plt.bar(Subject,Percentage,align='center',color='green')
plt.xlabel('Subject Name')
plt.ylabel('Pass Percentage')
plt.title('Bar Graph for Result Analysis:')
plt.savefig("E:/Sree Vidyanikethan International School/Practical/barg.png")
plt.show( )

Output:

Result: Thus, the program for given the school result data, analyses the performance of
the students on different parameters, e.g subject wise or class wise has been created and
executed successfully.

Class 12 – IP – Lab Programs 22


Program - 17: The Data frames created above analyze and plot appropriate charts with
title and legend.

Source Code:
import matplotlib.pyplot as plt
import numpy as np
s=['1st','2nd','3rd']
per_BPCC=[95,89,77]
per_MPCC=[90,93,75]
per_COMMERCE=[97,92,77]
x=np.arange(len(s))
plt.bar(x,per_BPCC,label='BPCC',width=0.25,color='green')
plt.bar(x+.25,per_MPCC,label='MPCC',width=0.25,color='red')
plt.bar(x+.50,per_COMMERCE,label='COMMERCE',width=0.25,color='yellow')
plt.xticks(x,s)
plt.xlabel("Position")
plt.ylabel("Percentage")
plt.title("Bar Graph for Result Analysis")
plt.legend( )
plt.savefig("E:/Sree Vidyanikethan International School/Practical/barg1.png")
plt.show( )

Output:

Result: Thus, the program for the Data frames created above, analyze and plot
appropriate charts with title and legend has been created and executed successfully.

Class 12 – IP – Lab Programs 23


Program - 18: Take data of your interest from an open source (e.g. data.gov.in),
aggregate and summarize it. Then plot it using different plotting functions of the
Matplotlib library.

Source Code:
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv("E:/Sree Vidyanikethan International School/Practical\census.csv")
print(df)

CSV File:
S.No.,State/UT,Population(Cr)
1,AP,5
2,TN,4.9
3,KL,3
4,KA,4
5,TS,3
6,MH,8
7,MP,6
8,HP,2.5

Output:
S.No. State/UT Population(Cr)
0 1 AP 5.0
1 2 TN 4.9
2 3 KL 3.0
3 4 KA 4.0
4 5 TS 3.0
5 6 MH 8.0
6 7 MP 6.0
7 8 HP 2.5

Class 12 – IP – Lab Programs 24


Source Code:

import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv("E:/Sree Vidyanikethan International School/Practical\census.csv")
slices=(df['Population(Cr)'].head(8))
states=(df['State/UT'].head(8))
plt.bar(states,slices,color='red',linewidth=3)
plt.title('2015 Census data')
plt.xlabel('States')
plt.ylabel('Population')
plt.savefig("E:/Sree Vidyanikethan International School/Practical/bar.png")
plt.show( )

Output:

Result: Thus, the program for data taken from CSV file, aggregated and summarized it.
Then plotted it using bar function of the Matplotlib library has been created and
executed successfully.

Class 12 – IP – Lab Programs 25

You might also like