You are on page 1of 87

Practical file-पपपपपपपपपप

पपपप
in
Informatics practices-065
for
Session 2022-
23

School Logo here

Guided by: ________

(Designation) Submitted by: ___________


Roll.No-________________

School name here


Certificate
This is to certify that
____(name)_________ , Roll No. _______
of class _____ Session 2022-23 has prepared
the Practical File as per the prescribed
Practical Syllabus of Informatics Practices
Code-065, Class-12 AISSCE (CBSE) under my
supervision.
It is the original work done by him/her. His/
her work is really appreciable.
I wish him/her a very bright success.

__________________
Signature of Teacher.
Acknowledement
I would like to express my special thanks of gratitude
to my teacher Mr./Ms. __________________ as well
as our Principal ___________ who gave me the
golden opportunity to prepare this Practical File.
Secondly, I would also like to thank my parents and
friends who helped me a lot in finalizing this file within
the limited time frame.

Student's Name & Signature:


Roll no:
Index
S.No. Practical Description Page Teacher's
No. Sign.
Section-A (Data Visualization)

Section-B (Pandas Series)

Section-C (Pandas DataFrame)

Section-D (MySQL)
Section-A

DATA VISUALIZATION
PRACTICAL NO-1
Date:_______
PROBLEM: Write a python program to generate line graph with suitable title and
labels. Where x is the year of performance with values
2014,2015,2016,2017,2018 and 2019. And y axis shows the profit of a particular
company in Rs.(Millions).

SOLUTION:
''' A program to draw line chart showing
Yealy profit of a Company'''
import matplotlib.pyplot as plt
x1=[]
for i in range(2014,2020):
x1.append(i)
y1=[10000,5000,20000,17000,12000,7000]
# Plotting line
plt.plot(x1,y1,color='r',marker='^',
markeredgecolor='b', linestyle='dashed')
plt.grid()
plt.xlabel("Year ->", color='blue')
plt.ylabel("Profit Rs. (in Millions)->",color='blue')
plt.title("Metcalf and Hodkingson Pvt.\
Ltd.\n Yearly Profit Analysis",color='r')
plt.show() # Displaying the chart

CODING:
OUTPUT:
PRACTICAL NO-2
Date:_______
PROBLEM: Given the following data of rainfall in different zones of India in mm
for 12 months, Create multiple lines chart in a Figure to observe any trends from
Jan to Dec.
Zones Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
North 14 13 13 19 16 20 15 17 19 17 15 12
South 16 20 13 20 20 17 11 16 13 14 17 20

SOLUTION:

# To plot a graph showing salary of Employees


import matplotlib.pyplot as plt
label = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
y1 =[14,13,13,19,16,20,15,17,19,17,15,12]
y2=[16,20,13,20,20,17,11,16,13,14,17,20]
plt.plot(label, y1,linestyle='dashed',label='North Zone',marker='s',markeredgecolor='r')
plt.plot(label, y2,label='South Zone',marker='^',markeredgecolor='b')
plt.xlabel('Month->', fontsize=10, color='red')
plt.ylabel('Rainfall ( in mm)->', fontsize=10, color='red')
plt.title('ZONE WISE RAINFALL ANALYSIS', color='blue')
plt.grid()
plt.legend()
plt.show()
CODING:

OUTPUT:
PRACTICAL NO-3
Date:_______
PROBLEM: Consider the data given below. Create a bar chart depicting the
downloads of the app.

App Name App Price in Rs. Total


Downloads
Angry Bird 75 197000
Teen Titan 120 209000
Marvel Comics 190 414000
ColorMe 245 196000
Fun Run 550 272000
Crazy Taxi 55 311000
Igram Pro 175 213000
WApp Pro 75 455000
Maths Formulas 140 278000

SOLUTION:
# To plot a graph showing salary of Employees
import matplotlib.pyplot as plt
import numpy as np
apps = ['Angry Bird','Teen Titan','Marvel Comics', 'ColorMe','Fun Run','Crazy Taxi', 'Igram
Pro','Wapp Pro','Maths Formulas']
downloads =[197000,209000,414000,196000,272000, 311000,213000,455000,278000]
index=np.arange(len(apps))
plt.bar(index,downloads,color='g')
plt.xticks(index,apps,rotation=25)
plt.xlabel('Apps->', fontsize=4, color='green')
plt.ylabel('Total Downloads->', fontsize=12, color='green')
plt.title('APP DOWNLOADS ANALYSIS', color='magenta')
plt.grid()
plt.show()

CODING:

OUTPUT:
PRACTICAL NO-4
Date:_______

PROBLEM : Write a program in Python Pandas to create the following


DataFrame
“df” from a Dictionary. Draw line charts to show the plotting of score1
and score 2 for all batsman. Put legends and titles. Specify different colours
and line styles of your choice for both the plotted lines. Change font size of
the titles to 15 and color to green.

B_No Name Score1 Score2


1 M.S. Dhoni 95 80
2 Virat Kohli 85 92
3 Sachin 110 75
4 Kartik 75 80
SOLUTION:

import matplotlib.pyplot as plt


import pandas as pd
dict1={'name':['M.S. Dhoni','Virat Kohli','Sachin','Kartik'],
'score1':[90,65,70,80],
'score2':[80,45,90,76],
'location':['Ranchi','Delhi','Mumbai','Delhi']}
df=pd.DataFrame(dict1,index=[1,2,3,4])
print(df)
df.plot(x='name',y=['score1','score2'],kind='bar', rot=25)
plt.title('Cricket Score Analysis of Batsman', fontsize=17, color='r')
plt.xlabel('Name of Batsman',fontsize=14,color="green")
plt.ylabel('Scores',fontsize=14,color="green")
plt.legend()
plt.grid()
plt.show()

CODING:

OUTPUT:
PRACTICAL NO-5
Date:_______
PROBLEM: Given the ages of 80 participants in some game. Write a program to
plot a histogram from given data with 6 bins of your choice.

Data = [ 9,10,11,13,13,15,16,17,18,19,21,23,23,23,24,24,25,25,25,25,25,
26,26,27,27,27, 27, 29,30,30,30,30,31,33,34,34,35,36, 36,37,37,37,
38,39,40,40,40,41,42,43,43,39,30,31,32,33,34,35,36,37,38,39,36,37,38,
40,41,42,43,44,45,50,51,52,53,54,55,56,57,58]

SOLUTION:

# To plot histogram for showing Ages of participants


# in different ranges
import matplotlib.pyplot as plt

data=[ 9,10,11,13,13,15,16,17,18,19,21,23,23,23,24,24,25,
25,25,25,25, 26,26,27,27,27, 27, 29,30,30,30,30,31,
33,34,34,35,36, 36,37,37,37, 38,39,40,40,40,41,42,43,
43,39,30,31,32,33,34,35,36,37,38,39,36,37,38,
40,41,42,43,44,45,50,51,52,53,54,55,56,57,58]
b=[0,10,20,30,40,50,60]
plt.hist(data,bins=b,color='g',edgecolor='b')
plt.title("Participants of Game in different Age Groups",
color='r', fontsize=16)
plt.xlabel("Age interval -->",fontsize=14, color='b')
plt.ylabel("No. of Participants -->",fontsize=14, color='b')
plt.show()

CODING:

OUTPUT:
Section-B
Pandas Series

PRACTICAL NO-6
Date:_______
PROBLEM: Create a Series from a Dictionary and another series using n-d array.
( Create the dictionary with month name as key and no. of days as value and
create a 1-d array of n integers.)

SOLUTION:
# Creating a Series using Dictionary
# as well as from an ndarray
import pandas as pd
import numpy as np
# Creating Dictionary
dict1=dict()
n=int(input("How many months ?"))
for i in range(1,n+1):
key=input("Enter month name( like JAN for January )")
value=int(input("Enter number of days:"))
dict1[key]=value
# Series creation from dictionary
s1=pd.Series(dict1)
print()
print("OUTPUT SERIES1")
print("**************")
print(s1)
# List creation
lst=[]
n=int(input("How many elements in array?"))
for i in range(n):
element=eval(input("Enter a number ?"))
lst.append(element)
# Array creation
arr1=np.array(lst)
# Series creation from array
s2=pd.Series(arr1)
print()
print("OUTPUT SERIES2")
print("**************")
print(s2)
# End of the Program

CODING:
OUTPUT:
PRACTICAL NO-7
Date:_______

PROBLEM: Create two series S1 and S2 using range function to perform various
mathematical operations (+, - , *, /) on both the series.

SOLUTION:
import pandas as pd
lower=int(input("Enter the lower limit of the first series"))
upper=int(input("Enter the upper limit of the first series"))
S=pd.Series(range(lower,upper))
print(S)
lower=int(input("Enter the lower limit of the second series"))
upper=int(input("Enter the upper limit of the second series"))
S1=pd.Series(range(lower,upper))
print(S1)
while(True):
print("Select the operation:")
print("1. Addition")
print("2. Substraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
ch=int(input("Enter choice:"))
if ch==1:
print(S+S1)
elif ch==2:
print(S-S1)
elif ch==3:
print(S*S1)
elif ch==4:
print(S/S1)
elif ch==5:
break
CODING:

OUTPUT:
PRACTICAL NO-8
Date:_______

PROBLEM: Create a Series, from List object, with user defined index, having
integer values. Now print the following attributes in the given format.

Attribute Name Series


Data type :
Shape :
No. of bytes
No. of Dimensions
Has NaNs ?
Empty?
Index
values
Shape

SOLUTION:

#Program 8
# Creating a Series using Array
import pandas as pd
import numpy as np
arr=np.array([15,20,25,30,35])
S1=pd.Series(arr)
print("Series: Integers")
print(S1)
gap=' '*3
heading=f"{'Attribute Name':20s}{gap}{'Series':7s}"
print()
print('-'*40)
print(heading)
print('-'*40)
print(f"{'Data Type:':20s}{gap}{str(S1.dtype):18s}")
print(f"{'No. of Bytes:':20s}{gap}{str(S1.nbytes):18s}")
print(f"{'No. of Dimensions:':20s}{gap}{str(S1.ndim):18s}")
print(f"{'Has NAN:':20s}{gap}{str(S1.hasnans):18s}")
print(f"{'Empty:':20s}{gap}{str(S1.empty):18s}")
print(f"{'Index:':20s}{gap}{str(list(S1.index)):18s}")
print(f"{'Values:':20s}{gap}{str(S1.values):18s}")
print(f"{'Shape:':20s}{gap}{str(S1.shape):18s}")
print('-'*40)
CODING:

OUTPUT:
PRACTICAL NO-9
Date:_______

PROBLEM: Write a program to accept the name and salary of n number of


employees and then create the series to store names as indexes and salary as
the data. Now the program must accept the name of the employee whose salary
needs to be changed and the new salary of the employee and then update it
in Series.

SOLUTION:

import pandas as pd
n=int(input("How many employees: "))
name=[]
sal=[]
for i in range(n):
a=input("Enter name: ")
b=int(input("Enter salary : "))
name=name+[a]
sal=sal+[b]
S=pd.Series(sal,index=name)
print(S)
chk=input("Enter the name of employee whose salary needs to be
changed : ")
new_sal=int(input("Enter the updated salary: "))
S[chk]=new_sal
print("The Series after updating the salry is\n",S)

CODING:
OUTPUT:
PRACTICAL NO-10
Date:_______

PROBLEM: Write a menu driven program to create and manipulate a series


elements using various series functions.

SOLUTION:

import pandas as pd
n=int(input("How many employees: "))
name=[]
sal=[]
for i in range(n):
a=input("Enter name: ")
b=int(input("Enter salary : "))
name=name+[a]
sal=sal+[b]
S=pd.Series(sal,index=name)
print(S)
while(True):
print("MENU OPTIONS:")
print("1. Top n elements")
print("2. Bottom n elements")
print("3. Conditional Filtering")
print("4. Sort elements")
print("5. Sort Index wise")
print("6. Delete elements")
print("7. Exit")
ch=int(input("Enter choice:"))
if ch==1:
no=int(input("Enter no. of elements : "))
print(S.head(no))
elif ch==2:
no=int(input("Enter no. of elements : "))
print(S.tail(no))
elif ch==3:
sal=eval(input("Enter Salary to be retrieved : "))
print(S[S==sal])
elif ch==4:
typ=input("Enter Order:")
if typ=='asc':
ord=True
else:
ord=False
S=S.sort_values(ascending=ord)
print(S)
elif ch==5:
typ=input("Enter Order:")
if typ=='asc':
ord=True
else:
ord=False
S=S.sort_index(ascending=typ)
print(S)
elif ch==6:
lst=eval(input("Enter list of index to be deleted for:
"))
S.drop(lst,inplace=True)
print(S)
elif ch==7:
break

CODING:
OUTPUT:
PRACTICAL NO-11
Date:_______

PROBLEM: Write a python program to create two series i.e. population and
average income of 4 metro cities, and then calculate per capita income storing in
third pandas series. Print it in a well formatted way.

SOLUTION:
#Calculating per capita income
import pandas as pd
population=pd.Series([30291000,20411000,14850000,10971000],
index=['Delhi','Mumbai','Kolkata','Chennai'])
avgincome=pd.Series([11787530613000,5874285800000,1718857800000,

2350383156000],index=['Delhi','Mumbai','Kolkata','Chennai'])
perCapitaIncome=avgincome/population

gap="| "
heading=f" {'City':<10s}{gap}{'Population':<11s}\
{gap}{'Average
Income(Rs.)':<20s}{gap}{'PerCapitaIncome(Rs.)':<20s}"
print()
print(f" {'M E T R O C I T Y : P E R - C A P I T A I N
C O M E '}")
print(f"
{'*********************************************************'}")
print()
print('-'*75)
print(heading)
print('-'*75)

L=len(population)
for i in range(L):
print(f"
{str(population.index[i]):<10s}{gap}{str(population[i]):<11s}\
{gap}{str(avgincome[i]):<20s}{gap}{str(perCapitaIncome[i]):<20s}"
)
print('-'*75)
CODING:

OUTPUT:
Section-C

Pandas DataFrame
PRACTICAL NO-12
Date:_______

PROBLEM: Write a Python program to create a DataFrame as given below, and


display all its attributes ( index, columns, shape, size, axes, rows and columns.
Rollno Name Year Percentage
10E01 AMAN 1982 98.5
12E05 RAGHAV 1984 86.9
10E12 RISHI 1982 76.6
12E15 MANVI 1984 80.0
10E25 VIVEK 1982 87.5
SOLUTION:
# Data Frame attributes
import pandas as pd
dict1={'Rollno':['10E01','12E05','10E12','12E15','10E25'],
'Name':['AMAN','RAGHAV','RISHI','MANVI','VIVEK'],
'Year':[1982,1984,1982,1984,1982],
'Percentage':[98.5,86.9,76.6,80.0,87.5]}
df=pd.DataFrame(dict1)
line='-'*65
print(line)
print(df)
print(line)
print("Index=",list(df.index))
print(line)
print("columns=",list(df.columns))
r,c=df.shape
print(line)
print("Shape : ",df.shape,"Rows=",r,"Columns=",c)
print(line)
print("Size : ",df.size)
print(line)
print("Axes :",df.axes)
print(line)
print("Rows :",df.values)
print(line)
print("Columns :",df.columns)
print(line)
CODING:

OUTPUT:
PRACTICAL NO-13
Date:_______

PROBLEM: Considering the given dataframe Books, accept the Book Number of
a book ( given as index) from the user and display all its details. The program
must continue executing till the user wants. The program must give a valid output
if the Book Number entered for searching is not there in the dataframe.

SOLUTION:

import pandas as pd
dct={'Bookname':['Biology for 12','Physics for 12','Maths for
12','Comp Sc for 12','IP for 12'],
'Author':['K N Bhatia','S L Arora','R S Aggarwal','Sumita
Arora','Preeti Arora'],
'Price':[570,820,450,485,490],
'Publisher':['TRUEMEN','DHANPAT RAI','DHANPAT RAI','DHANPAT
RAI','S CHAND'],
'Copies':[100,150,200,250,200]
}
Books=pd.DataFrame(dct, index=[1001,1002,1003,1004,1005])
print(Books)
ch="y"
while(ch=='y'or ch=='Y'):
bno=int(input("Enter the Book number to search for :"))
if bno in Books.index:
print(Books.loc[bno])
else:
print("Sorry ! This Book number doesn't exists in this
DataFrame")
ch=input("Do you want to search for more Books? [Y/N]")
else:
print("Thank you. See you next Time....")

CODING:
OUTPUT:
PRACTICAL NO-14
Date:_______

PROBLEM : Considering the given dataframe Books, Now write a menu driven
program to add a new Row of record and Delete any book/row as per the user's
choice.

SOLUTION :

import pandas as pd
dct={'Bookname':['Biology for 12','Physics for 12','Maths for
12',
'Comp Sc for 12','IP for 12'],
'Author':['K N Bhatia','S L Arora','R S Aggarwal','Sumita
Arora','Preeti Arora'],
'Price':[570,820,450,485,490],
'Publisher':['TRUEMEN','DHANPAT RAI','DHANPAT RAI','DHANPAT
RAI','S CHAND'],
'Copies':[100,150,200,250,200]
}
Books=pd.DataFrame(dct, index=[1001,1002,1003,1004,1005])
print(Books)
while(True):
print("MENU")
print("1. Add a new Book (Row)")
print("2. Delete an old Book")
print("3. Exit")
n=int(input("Enter choice (1-3): "))
if n==1:
ch="y"
while(ch=='y'or ch=='Y'):
bno=int(input("Enter the Book number: "))
bnm=input("Enter Book name: ")
aut=input("Enter Author: ")
prc=int(input("Enter Price: "))
pub=input("Enter Publisher: ")
nob=input("Enter No. of Copies: ")
Books.loc[bno]=[bnm,aut,prc,pub,nob]
print("The new dataframe with the added Book:")
print(Books)
ch=input("Do you want to add more Books? [Y/N]")
elif n==2:
ch="y"
while(ch=='y'or ch=='Y'):
bno=int(input("Enter the Book number: "))
if bno in Books.index:
Books.drop(bno,inplace=True)
print("The Book has been deleted Successfully.")
print()
print("Books Record after deletion.")
print(Books)
else:
print()
print("This book does not exists in the
DataFrame")
ch=input("Do you want to add more Books? [Y/N]")
else:
print("Thank you. See you next Time....")
break

CODING :
OUTPUT :
PRACTICAL NO-15
Date:_______

PROBLEM : Considering the given dataframe empdf, Now write a menu driven
program to retrieve the records as per the following conditions.

a) To display those employees whose bonus>= entered bonus


b) To display all those records whose Salary lies in the range of x and y.
c) To display empcode, ename,salary & job for the entered job only.
d) To display those records for two entered zone only.
e) To display Ename, Job and Salary of those Employees whose job and salary
is entered by the user.

SOLUTION :

# Conditional query from a Pandas Data Frame


import pandas as pd
dict1={'Empcode':['E101','E102','E102','E103','E104'],
'Ename':['Sam','Kain','Scott','Joy','Tom'],
'Job':['Clerk','Manager','Clerk','Analyst','Manager'],
'Salary':[20000,50000,18000,55000,65000],
'Bonus':[1000,2500,1000,7000,5000],
'Zone':['West','East','East','North','West']}
empdf=pd.DataFrame(dict1,index=[10,20,30,40,50])
line='-'*80
print("Data Frame:")
print(empdf)
while True:
print(''' MENU
******
-------------------------------------------------------------
-----------
1- To display those employees whose bonus is >= input value?
2- To display all those records whose Salary lies in the
entered range
3- To display empcode, ename, salary and job for entered job
4- To display records of two entered zones only
5- To display Ename, Job & Salary of entered job and Salary
6- E X I T
-------------------------------------------------------------
-----------''')
ch=int(input("Enter Your Choice(1-6)"))
if ch==1:
bns=float(input("Enter Bonus value[1000-6000]"))
print(line)
print("1)To display those employees whose bonus is
>=",bns)
print(empdf[empdf['Bonus']>=bns])
print(line)
elif ch==2:
print(line)
lower=int(input("Enter lower range:"))
upper=int(input("Enter upper range:"))
print("2)To display records whose Salary lies in the
range",lower,"to",upper)
print(empdf[(empdf['Salary']>=lower) &
(empdf['Salary']<=upper)])
print(line)
elif ch==3:
jb=input("Enter the Job:")
print(line)
print("3) To display empcode,ename,salary & job for the
job-",jb)

print(empdf.loc[empdf['Job']==jb,['Empcode','Ename','Salary','Job
']])
print(line)
elif ch==4:
zone1=input("Enter Zone-1:")
zone2=input("Enter Zone-2:")
print(line)
print("4) To display records of two entered zones only
only.")
print(empdf[(empdf['Zone']==zone1) |
(empdf['Zone']==zone2)])
print(line)
elif ch==5:
jb=input("Enter Job for its Salary retrieval:")
sl=int(input("Enter Salary:"))
print(line)
print('''5) To display Ename, Job and Salary of entered
job''',jb,"and salary",sl)
print(empdf.loc[(empdf['Job']==jb) &
(empdf['Salary']==sl),['Ename','Job','Salary']])
print(line)
else:
print("Thank you so much. See you.")
break
CODING :
OUTPUT :
PRACTICAL NO-16
Date:_______

PROBLEM : Consider a csv file named “Student” from e:\akp\ and write a menu
driven program to create dataframes from the given csv with the following
specifications:

(a) Read csv and transfer it to a dataframe stdf.


(b) Accept the column names which the user wants to include in the
dataframe
(c) Accept the number of rows user wants to skip from the csv while
creating the dataframe.
(d) Write the updated dataframe into a new csv file named "student1"

SOLUTION:

import pandas as pd
global stdf
while True:
print("MENU")
print("******")
print("1. Read a csv Student.csv and Create a DataFrame
stdf")
print("2. Accept the column names which the user wants to
include in the dataframe")
print("3. Accept the number of rows reading from the top of
csv to creat the dataframe.")
print("4. Write the updated dataframe into a new csv file
named student1.csv")
print("5. Exit")
ch=int(input("Enter choice [1-5]: "))
if ch==1:
path=input("Enter the csv file name with path: ")
stdf=pd.read_csv(path)
print(stdf)
if ch==2:
path=input("Enter the csv file name with path: ")
y=eval(input("Enter the column names you want to include
in the dataframe: "))
stdf=pd.read_csv(path,usecols=y)
print(stdf)
elif ch==3:
path=input("Enter the csv file name with path: ")
n=eval(input("Enter the number of rows you want to read
from the csv: "))
stdf=pd.read_csv(path,nrows=n)
print(stdf)
elif ch==4:
path=input("Enter the csv file name with path for
writing: ")
stdf.to_csv(path,index=False)
print(stdf)
elif ch==5:
print("Happy Coding. See you....")
break
CODING:

OUTPUT:
PRACTICAL NO-17
Date:_______

PROBLEM : Write a menu driven python program to create a DataFrame with


marks of 5 students in 5 subjects. And the handle the following options using
menu.

(a) Add a column Total showing sum of marks of all subjects.


(b) Now increase 5 marks in the 'Total' column for all students
(c) Add one more column Percentage, calculated on the basis of
'Total' marks obtained out of 500
(d) Add a new row in the above DataFrame.( Using loc)
(e) Now modify the English marks of Thomas as 70,accordingly update his Total
and percentage.
(f) Add two more rows together in the above dataFrame.( Using append)

SOLUTION:

# A Menu Driven Program


import pandas as pd
global df
name=['Scott','Michel','Thomas','Mathews','David']
eng=[78,75,67,80,87]
mat=[79,90,85,90,95]
phy=[87,57,76,8,78]
chem=[97,92,80,80,59]
info=[94,97,90,99,100]
df=pd.DataFrame({'Sname':name,'English':eng,'Maths':mat,\
'Physics':phy,'Chemistry':chem,'Info.Pr.':info})
line='-*'*40
print("DataFrame :")
print(df)
print(line)

# Defining functions
def add_col():
#df['Total']=df.sum(axis=1)

df['Total']=df['English']+df['Maths']+df['Physics']+df['Chemistry
']+df['Info.Pr.']
print(df)
print(line)

def incr5():
df['Total']=df['Total']+5
print(df)
print(line)

def add_per():
df['Percentage']=df['Total']*100/500
print(df)
print(line)

def add_newrow():
df.loc[5]=['Joe',65,78,89,76,90,398,79.6]
print(df)
print(line)
def add_tworows():

df1=pd.DataFrame({'Sname':['Martin','Sam'],'English':[90,89],'Mat
hs':[99,80],
'Physics':[82,67],'Chemistry':[78,60],'Info.Pr.':[98,80],'Total':
[447,376],
'Percentage':[89.4,75.2]})
df2=df.append(df1,ignore_index=True)
print(df2)
print(line)
def modi_eng():
df.loc[2,['English']]=70

df['Total']=df.English+df.Maths+df.Physics+df.Chemistry+df['Info.
Pr.']
df['Total']=df['Total']+5
df['Percentage']=df['Total']*100/500
print(df)
print(line)

# Main program
while True:
print()
print("***** M E N U D R I V E N P R O G R A M *****")
print("================================================")
print("a) Add a column Total showing sum of marks of all
subjects.")
print("b) Now increase 5 marks in the 'Total' column for all
students.")
print('''c) Add one more column Percentage, calculated on the
basis of
'Total' marks obtained out of 500.''')
print("d) Add a new row in the above DataFrame.( Using loc)")
print('''e) Now modify the English marks of Thomas as 70,
accordingly update his Total and percentage.''')
print("f) Add two more rows together in the above dataFrame.(
Using append)")
print("x) E X I T")
ch=input("Enter your choice:(a-g)")
if ch=='a':
add_col()
if ch=='b':
incr5()
if ch=='c':
add_per()
if ch=='d':
add_newrow()
if ch=='e':
modi_eng()
if ch=='f':
add_tworows()
if ch=='x':
break

CODING:
OUTPUT:
PRACTICAL NO-18
Date:_______

PROBLEM : Write a python program to represent binary operation of two


DataFrames Using add(), sub(), mul() and div() function

SOLUTION :

# Binary Operation on DataFrame


# Using add(), sub(), mul() and div() function
import pandas as pd
import numpy as np
student1={'CT-1':[5,6,8,np.nan,10],'CT-2':[7,8,9,6,15]}
student2={'CT-1':[3,3,6,6,8],'CT-2':[5,9,np.nan,10,5]}
df1=pd.DataFrame(student1)
df2=pd.DataFrame(student2)
print("Data Frame1 :")
print(df1)
print("Data Frame2 :")
print(df2)
line='='*75
while True:
print(line)
print("\t\t\tM A I N M E N U")
print(line)
print("\t\t1- Add 2 Data Frames")
print("\t\t2- Subtract 2 Data Frames")
print("\t\t3- Multiply 2 Data Frames")
print("\t\t4- Divide 2 Data Frames")
print("\t\t5-E x i t")
print(line)
choice=int(input("\t\tEnter your choice(1-5) :"))
print(line)
if choice==1:
print("Addition :")
print(df1.add(df2))
# OR print(df1+df2)
if choice==2:
print("Subtraction :")
print(df1.sub(df2))
# OR print(df1-df2)
if choice==3:
print("Multiplication :")
print(df1.mul(df2))
# OR print(df1*df2)
if choice==4:
print("Division :")
print(df1.div(df2))
# OR print(df1/df2)
if choice==5:
print("Thank you. Exiting.....")
break

CODING :
OUTPUT :
PRACTICAL NO-19
Date:_______

PROBLEM : Write a python program to represent the use of iterrows() and


iteritems() in a DataFrame through menu driven.

SOLUTION :

# To display quarterly sales


import pandas as pd
qtr=['Qtr1','Qtr2','Qtr3','Qtr4']
year1=[3500,5600,3300,4500]
year2=[5500,4600,6700,8900]
year3=[9000,7800,7800,2200]
dct={'yr1':year1,'yr2':year2,'yr3':year3}
df=pd.DataFrame(dct,index=qtr)
print("a) Data Frame :")
print(df)
line='='*75
while True:
print(line)
print("\t\t\tM A I N M E N U")
print(line)
print("\t\t1- For extracting data row-wise")
print("\t\t2- For extracting data row-wise Series Objects")
print("\t\t3- For extracting data column-wise")
print("\t\t4-E x i t")
print(line)
choice=int(input("\t\tEnter your choice(1-3) :"))
print(line)
if choice==1:
for index, row in df.iterrows():
print("Row index :",index)
print("Containing :")
print(row)
if choice==2:
for (index, rowseries) in df.iterrows():
print("\tRow index :",index)
print("\tContaining :")
i=0
for val in rowseries:
print('\t\tAt',i,"Position",val)
i+=1
if choice==3:
for col, content in df.iteritems():
print("Column :",col)
print("Content :")
print(content)
if choice==4:
print("Thank you. Exiting....")
break

CODING:
OUTPUT:
PRACTICAL NO-20
Date:_______

PROBLEM : Write a python program to create the following dataframe namely


aid_df that stores the aid by NGOs for different states.
Now display the following:
a) Show the data of toy column
b) Show tha data of books and uniform columns
c) Show the data of toy and uniform columns for top 3 rows ( use loc)
d) Show the data of top 3 rows and first 3 columns ( use iloc)
e) Now set the index state as index and display the dataframe
f) Now show the data for toys, uniform and shoes columns of Andhra, Bihar
and W.B.
g) Now reset the index and show the dataframe

SOLUTION :

# To set up query from a DataFrame


import pandas as pd
Lstate=['Andhra','Odisha','Bihar','Jharkhand','W.B.']
Ltoys=[4656,5767,6784,1243,5766]
Lbooks=[34445,45554,45848,56574,56575]
Luniform=[100,500,500,488,399]
Lshoes=[400,600,688,700,456]
dict1={'State':Lstate,'Toys':Ltoys,'Books':Lbooks,
'Uniform':Luniform,'Shoes':Lshoes}
aid_df=pd.DataFrame(dict1)
line='-='*40
print(line)
print("Original DataFrame:")
print(aid_df)
print(line)
print("a) Show the data of toy column")
print(aid_df[['Toys']])
print(line)
print("b) Show the data of Books and Uniform columns")
print(aid_df[['Books','Uniform']])
print(line)
print("c) Show the data of Toys and Uniform Column for top 3 rows
( Use loc)")
print(aid_df.loc[:2,['Books','Uniform']])
print(line)
print("d) Show the data of first 3 rows and first 3 columns(
using iloc)")
print(aid_df.iloc[:3,:3])
print(line)
print("e) Now set the state as index and display the dataframe")
aid_df=aid_df.set_index(['State'])
print(aid_df)
print(line)
print('''f) Now show the data for Toys, Uniform
and Shoes columns of Andhra ,bihar and W.B''')
print(aid_df.loc[['Andhra','Bihar','W.B.'],['Toys','Uniform','Sho
es']])
print(line)
print("g) Now reset the index and show the dataframe")
aid_df=aid_df.reset_index()
print(aid_df)
print(line)

CODING:
OUTPUT:
Section-D
MySQL
Practical No-21
Date: ________
Problem- Create a database 'School' on the database server, show the list of databases
and open it.
Solution :
> create database school;
> show databases;
> use school;

Command and output ( Screenshot ) :


Practical No-22
Date: ________
Problem- Create the following table named 'STUDENT' with appropriate data type, size
and constraint(s) if any. Show its table structure also.

Solution :
create table student(Name varchar(10), class char(3), dob date, sex char(1),
City varchar(10), Marks int(3));

Table structure:

Command : desc student;


Practical No-23
Date: _________
Problem- insert few records/tuples into the table. Verify the entered records.
Solution :
insert into student values('Nanda', 'X', '1995-06-06','M','Agra',451);
Note : issued similar commands for other records.

Record verification:
Practical No-24
Date: __________
Problem- Display all the information of males whose city is NEITHER Delhi or Mumbai.
Solution-
select * from student where city not in ('Delhi', 'Mumbai');

Practical No-25
Date: __________
Problem- Display the details of all the students whose date of birth is after Nishant’s Birth date
1995-12-06. (consider the Sql’s standard date format)
Solution:
select * from student where dob>'1995-12-06';
Practical No-26
Date: __________

Problem- Display all information about class XII students rank wise.
Solution:
select * from student where class='XII' order by marks desc;

Practical No-27
Date: _________

Problem-Display all columns arranged in descending order of city and within the city in the ascending
order their marks.
Solution:
select * from student order by city desc, marks;
Practical No-28
Date: __________

Problem- List names of all students whose name has the character ‘a’.
Solution:
select Name from student where name like '%a%';

Practical No-29
Date: __________
Problem- Display Name and Marks of those students whose marks is in the range 400 and 500
( both are inclusive)
Solution:
select Name, Marks from student where marks between 400 and 500;
Practical No-30
Date: __________

Problem- Display average marks, highest marks and total no. of students for each class
Solution:
select Class, avg(Marks), Max(Marks), Count(*), from student group by Class;

Practical No-31
Date: __________
Problem- Display total no of males and females separately, along with their average marks.
Solution:
select Sex, count(*) from student group by sex;
Practical No-32
Date: __________
Problem- Increase the marks of 10th class students by 5% marks and verify the updated
rows.

Solution:
update student set marks=marks+(marks*0.05) where class = 'X';
Practical No-33
Date: __________
Problem- Add a new column named Address. ( Take the data type and size yourself) and
verify the table structure.
Solution:
Alter table student add address varchar(25);

Practical No-34
Date: __________
Problem- Add Primary key to the column Name.
Solution:
Alter table student add primary key(Name);
Practical No-35
Date: _________
Problem- Display name, class and city of 'XII' class students who lives in 'Mumbai'.
Solution:
Select Name, Class, City from student where class='XII' and City='Mumbai';

Practical No-36
Date: _________
Problem- Display unique sex names.
Solution:
Select distinct sex from student;
Practical No-37
Date: __________
Problem- Display name, data of birth and day name (like Sunday, Monday,.), of all females,
whose marks is greater than or equal to 400.
Solution:
Select Name, dob, dayname(dob), Marks, from student where sex='F' and Marks>=400;

Practical No-38
Date: _________
Problem- Display City and highest marks of students of each city, but only for Delhi and
Mumbai.
Solution:
Select city, max(Marks) from student group by city having city in('Delhi','Mumbai');
Practical No-39
Date: ________
Problem- Display City and highest marks of students of each city, but only for Delhi and
Mumbai in descending order of city.
Solution:
Select city, max(Marks) from student group by city having city in('Delhi','Mumbai') order
by city desc;

Practical No-40
Date: __________
Problem- Display round of average marks up to zero places, truncate of average marks up to 1
decimal place for class 'X' students only.
Solution:
Select round(avg(marks),0), truncate(avg(marks),1) from student where class='X'
Practical No-41
Date: _________
Problem- Write a query to display name and the position of character 'a' in the names of
students having 'a' anywhere in their names.
Solution:
Select name, instr(name,'a') from student where name like '%a%';

Practical No-42
Date: ________
Problem- Display name, character number 3rd and 4th of each name and counting of number
of characters in each name.
Solution:
Select name, substr(name,3,2), length(name) from student;
Practical No-43
Date: ________
Problem- Display current date and current time together.
Solution:
Select curdate() as "Current Date", curtime() as "Current Time";

Practical No-44
Date: ________
Problem- Display name, marks and round up the Square root of marks up to 2 decimal places
Solution:
Select Name, Marks, round(sqrt(Marks),2) from student;
Bibliography
1- Text Book by: ________________ Class XI - IP

2- Text Book by: ________________ Class XII - IP

3- NCERT Text book Class XI - IP

4- NCERT Text book Class XII - IP

5- Google.com for various searches

6- ............................

7- ............................

8- Class Notes

Teacher's Signature:

_____________________

You might also like