Professional Documents
Culture Documents
पपपप
in
Informatics practices-065
for
Session 2022-
23
__________________
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.
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:
OUTPUT:
PRACTICAL NO-3
Date:_______
PROBLEM: Consider the data given below. Create a bar chart depicting the
downloads of the app.
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:_______
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:
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.
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:_______
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:_______
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:_______
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.
SOLUTION :
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:
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:_______
SOLUTION:
# 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:_______
SOLUTION :
CODING :
OUTPUT :
PRACTICAL NO-19
Date:_______
SOLUTION :
CODING:
OUTPUT:
PRACTICAL NO-20
Date:_______
SOLUTION :
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;
Solution :
create table student(Name varchar(10), class char(3), dob date, sex char(1),
City varchar(10), Marks int(3));
Table structure:
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
6- ............................
7- ............................
8- Class Notes
Teacher's Signature:
_____________________