0% found this document useful (0 votes)
10 views60 pages

Informatics Practices Record Class 12

This document is a record of Informatics Practices for the academic year 2023-24, detailing various programming exercises and projects using Python and Pandas. It includes tasks related to data handling, data visualization, and data management, along with corresponding dates and signatures. The document also contains coding examples demonstrating the implementation of these tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views60 pages

Informatics Practices Record Class 12

This document is a record of Informatics Practices for the academic year 2023-24, detailing various programming exercises and projects using Python and Pandas. It includes tasks related to data handling, data visualization, and data management, along with corresponding dates and signatures. The document also contains coding examples demonstrating the implementation of these tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

INFORMATIC PRACTICES

RECORD
ACADEMIC YEAR : 2023-24

CBSE ROLL NO:

NAME:

CLASS:

SUBJECT: INFORMATICS PRACTICES

SUB CODE:065

INDEX
S.NO DATE PROGRAMS PAGE NO SIGNATURE

DATA HANDLING –PYTHON PANDAS

Creation of data frame from list of


1. 12/4/2023
dictionaries –Get input from user .

Dataframe – Total expenditure per


2. 12/4/2023
product

Write a Pandas program to sort the data


frame first by
13/4/2023
3. 'Designation' in Ascending order, then
by 'Name' in Descending order.

Create a pandas series from a dictionary


4. 13/4/2023
of values and an ndarray.

Write a Pandas program to convert a


5. 26/4/2023 Pandas module Series to Python list and
it’s type

Write a Pandas program to add, subtract,


6. 26/4/2023
multiple and divide two Pandas Series

Pythonprogramtofindthe
sum,average,min,max,count of weekly

13/5/2023 expenses of
7.
series s1 using pandas and finally sort the
given series into new series S2

Given a Series, print all the elements


13/5/2023
8. that are above the 75th percentile.

Create a data frame for examination


result and display
9. 18/5/2023 row labels, column labels data types of
each column and the dimensions

Filter out rows based on different


20/5/2023
10. criteria such as duplicate rows.

Pandas program to select the name of


20/5/2023
11. persons whose height is between 5 to 5.5

Python program to find the total marks


obtained and percentage of marks of
12. 25/5/2023 each student.

Highest, lowest, and mean of marks


27/5/2023
13. obtained by students.

Write a program to create dataframe for


3 student including name and roll
numbers and also add new columns for
14. 30/5/2023 5 subjects and 1 column to calculate

percentage.

Importing and exporting data between


pandas and CSV file .Dataframe should
15. 7/6/2023 be created dynamically.
Python program to transfer the data from
9/6/2023
16. dataframe to mysql table

Python program to transfer the data


13/6/2023
17. from mysql to dataframe

DATA VISUALIZATION

Given the school result data, analyse the


performance of the students on different

18. 15/6/2023 parameters, e.g subject wise or class


wise.

Python program to plot multiple bar


graph to visualize the toppers in three
19. 17/6/2023 subjects using the data Series (PANDAS)

Python program to plot horizontal bar


20. 20/6/2023 graph depicting the popularity of various
programming languages.

Python program to plot a quadratic


equation using dashed line chart.1-
21. 22/6/2023 0.5*x**2

Python program to plot multiple line plot


to visualize the spread of covid-19 in UAE
for three months APR,MAY,JUNE,JULY
22. 24/6/2023 2020 with different linestyles and
markers

Python program to plot histogram to


visualize the frequency of commuters in
23. 25/6/2023 a shopping mall

Take data of your interest from an open


source (e.g. data.gov.in), aggregate and

24. 26/6/2023 summarize it. Then plot it using different


plotting functions of the Matplotlib
DATA MANAGEMENT

MYSQL Queries to create database


IP12 and
25. 5/9/2023
table “Student”.

MYSQL Queries to insert the given set


26. 7/9/2023
of records

MYSQL Queries to delete few


27. 9/9/2023
records and update few records

MySQL queries – SELECT with


28. 12/9/2023 different conditions

MYSQL Queries to implement all


Aggregate functions like
29. 14/9/2023 sum,min,max,avg,count(*),count()

MYSQLQueriestoimplementMath
function,text function,date and time
30. 16/9/2023 function
CODING:

import pandas as pd

n=int(input("ENTER THE NO OF ROWS IN THE DATAFRAME"))

#empty list creation l1=[]

#empty dictionary creation d={}

for i in range(0,n):

FName=input("Please enter the FName") LName=input("Please enter the LName")


d["FirstName"]=FName d["LastName"]=LName

print(d) l1.append(d.copy()) print(l1)

print("Thanks for entering the data") print("The list of dictionaries is:") print(l1)

#data frame creation using list of dictionaries df=pd.DataFrame(l1)

print("The dataframe is created successfully") print(df)

OUTPUT:
CODING:

import pandas as pd

itemname=['Ball Point Pen','Permanent Marker Pen','Whiteboard Marker Pen', 'A3


Paper Sheet','A4 Paper Sheet','Diary Large','Diary Small','Notebook Large-
Ruled','Notebook Medium- Ruled'] itemCategory=
['Pen','Marker','Marker','Paper','Paper','Dia ry','Diary','Notebook','Notebook'] price=
[20.00,40.00,50.00,320.00,300.00,189.00,90.50, 180.00,120.00]

data = {'Item Category': itemCategory, 'Item Name': itemname, 'Expenditure': price}


df_Company = pd.DataFrame(data) print(df_Company)

grpBy1 = df_Company.groupby('Item Category') print("Result after Filtering


Dataframe") print(grpBy1.sum())

OUTPUT:

CODING:

import pandas as pd

data1 = {'Name':['Akshat', 'Sameer', 'Pihu', 'Neha'] ,

'Age':[28,34,29,42], 'Designation':['Accountant' , 'Clerk',


'Clerk', 'Manager']}

df1 = pd.DataFrame(data1) print(df1.sort_values(by=['Designation','Name'],


ascending=[True,False]))

OUTPUT:

CODING:

#import pandas library as pdnd numpy library as np import numpy as np

import pandas as pd

#create a series s1 using ndarray s1=pd.Series(np.array([1,3,4,5,8,9,11,13,25,89]))


print("The Series created from ndarray:") print(s1)

#create a dictionary named dic dic={"jan":31,"feb":28,"mar":31,"apr":30} #create a


series s2 using dictionary dic s2=pd.Series(dic)

print("The Series created from dictionary:") print(s2)

OUTPUT:
CODING:

import pandas as pd

ds= pd.Series([2, 4, 6, 8, 10]) print("Pandas Series and type")


print("**********************") print("INDEX DATA")

print("")

print(ds) print(type(ds))

print("Convert Pandas Series to Python list") print(ds.tolist())

print(type(ds.tolist()))

OUTPUT:
CODING:

import pandas as pd
ds1= pd.Series([12,14, 26, 18,10])

ds2= pd.Series([1,3, 5, 7,5])

ds3= pd.Series([89,67,2])

ds = ds1 + ds2

print("Add two Series:ds1 and ds2")

print(ds)

ds = ds1 + ds3

print("Add two Series:ds1 and ds3")

print(ds)

print("Add two Series to avoid NAN")

print("with add function to handle missing values") print(ds1.add(ds3,fill_value=0))

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:
CODING:

#Python program to find the sum,average,min,max,count of weekly expenses and


to sort it into new series

import pandas as pd

IND=["MON-EXP","TUE-EXP","WED-EXP","THU-EXP","FRI- EXP","SAT-EXP"]

s1= pd.Series([100.5,200.8,78,92,300.12,400],index=IND)

print("The sum of all expenses in the week:",s1.sum()) print("The Average of all


expenses in the week:",round(s1.mean(),2))

print("The highest of all expenses in the week:",s1.max()) print("The lowest of all


expenses in the week:",s1.min()) print("The number of expenses in the
week:",s1.count()) print("Series before sorting:")

print(s1)

s2= pd.Series(s1).sort_values() print("Series After sorting:") print(s2)

OUTPUT:
CODING:

import pandas as pd import numpy as np

s=pd.Series(np.array([1,3,4,7,8,8,9])) print("The series:")

print(s) res=s.quantile(q=0.75)

print("75th Percentile of the given series is:") print(res)

print("The elements that are above the 75th percentile:") print(s[s>res])

OUTPUT:
CODING:

import pandas as pd dic={"CLASS":["I","II","III","IV","V","VI","VII","VIII","I


X","X","XI","XII"], "PASS- PERCENTAGE":[

99,98,100,98.6,97.2,99,100,97.9,100,100,99,100],

“TOPPER":["RAM","SHYAM","RAHUL","CHRISTOPHER","ROOPALI","V

ENKAT","KUMAR","SAHEEL","SALIM","POOJA","ANIL

KUMAR","GEETHA"],"NO-OF-STUDENTS”:
[230,450,390,412,290,300,234,345,213,300,112,111]}

result=pd.DataFrame(dic)

print("The dataframe created from dictionary:") print(result)

print("The datatypes of dataframe") print(result.dtypes)

print("The shape of the dataframe is:") print(result.shape)


OUTPUT:

CODING:

import pandas as pd dic={"NAME":


["MALA","SURESH","MALA","RAHUL","SURESH","RAHI
M","MALA"],"AGE" :[23,24,23,28,24,35,23], "SALARY":
[10000,45000,10000,72000,45000,67000,10000]}

df=pd.DataFrame(dic)

print("The Dataframe created is :") print(df)

#Find duplicate rows duplicaterow=df[df.duplicated(keep=False)] print("The


duplicate rows in the dataframe are:")
print("****************************************") print(duplicaterow)

OUTPUT:

CODING:

import pandas as pd import numpy as np

pers_data = {'name': ['Asha', 'Radha', 'Kamal',

'Divya','Anjali',"Kavitha"],

'height': [ 5.5, 5, np.nan, 5.9, np.nan,4.9],


'age': [11, 23, 22, 33, 22,23]}

labels = ['a', 'b', 'c', 'd', 'e','f']

df = pd.DataFrame(pers_data , index=labels) print("The dataframe created is:")


print(df)

print("Persons whose height is between 5 and 5.5") print(df[(df['height']>= 5 )&


(df['height']<= 5.5)]) OUTPUT:

CODING:

import pandas as pd

dct = {"SID":[1,5,7,8], "SNAME":["AKIL", "BALA",

"CATHARINE","DERRICK"],"MARKS1":[80,90,20,50],

"MARKS2":[82,91,30,40], "MARKS3":[91,95,80,70]}

df=pd.DataFrame(dct) print("The dataframe is:") print(df)

for i in df.index:

m1 = df.iloc[i]["MARKS1"]

m2 = df.iloc[i]["MARKS2"]
m3 = df.iloc[i]["MARKS3"] total = m1+m2+m3

per = total/3

print("Total marks obtained by ", df.iloc[i]["SNAME"],": ", total,"/400")

print("Percentage of ", df.iloc[i]["SNAME"],": ", format(per,'.2f'),"%")

print("")

OUTPUT:

CODING:
import pandas as pd dct = {"AdmNo":

[1024,2031,1233,4342],"Name":['Aman','Rahul',

'Saurab','Zoya'],

"Class":[12,9,11,12], "Gender":['B','B','B','G'], "Marks": [33, 73, 50, 95] }

df= pd.DataFrame(dct, index=['A', 'B', 'C', 'D']) print("The dataframe is:")

print(df)

print("Maximum marks: ", df['Marks'].max())

print("Minimum marks: ", df['Marks'].min()) print("Mean/Average marks: ",


df['Marks'].mean())

OUTPUT:

CODING:

import pandas as pd, numpy as np, random D={'Roll':[1,2,3],'Name':


['Sangeeta','Shanti','Swati']} PHY=[]

CHE=[]

BIO=[]
ENG=[]

IP=[]

SD=pd.DataFrame(D) #RANDOM NUMBER GENEARATION

for i in range(3): PHY.append(random.randint(1,101))


CHE.append(random.randint(1,101)) BIO.append(random.randint(1,101))
ENG.append(random.randint(1,101)) IP.append(random.randint(1,101))

SD['PHY']=PHY SD['CHEM']=CHE SD['BIO']=BIO

SD['ENG']=ENG SD['INFO_PRACTICES']=IP

SD['Total']=SD.PHY+SD.CHEM+SD.BIO+SD.ENG

+SD.INFO_PRACTICES

SD['Per']=SD.Total/5 print(SD)

OUTPUT:
CODING:

import pandas as pd df=pd.read_csv("E:/file2.csv") #IMPORTING DATA FROM CSV


TO DATAFRAME

print("IMPORTING DATA FROM CSV TO DATAFRAME")

print("************************************") print("The dataframe having


the csv file data") print("") print(df)

print("SUCCESSFULLY IMPORTED DATA FROM CSV TO DATAFRAME")

print("") n=int(input("ENTER THE NO OF ROWS IN THE DATAFRAME")) l1=[]

d={}

for i in range(0,n): shopid=int(input("enter the shopid")) shopname=input("enter the


shopname") loc=input("enter the location") d["shopid"]=shopid
d["shopname"]=shopname

d["loc"]=loc print(d) l1.append(d.copy()) print(l1)

print("Thanks for entering the data")

print("The list of dictionaries:") print(l1)

df1=pd.DataFrame(l1)

#THE CONTENTS OF DATAFRAME:

print("THE CONTENTS OF THE DATAFRAME WHICH IS TO BE EXPORTED TO CSV


FILE:")

print(df1)

#SAVING THE DATAFRAME


df1.to_csv("E:/dataframe1.csv")

print("SUCCESSFULLY EXPORTED DATA FROM DATAFRAME TO CSV")

OUTPUT:
OUTPUT:

OUTPUT:
CSV FILE WHICH IS IMPORTED :
EXPORTED DATA FROM DATAFRAME IS SAVED IN THE FOLLOWING CSV FILE:

CODING:
#python program to transfer the data from dataframe to mysql table

import pandas as pd import mysql.connector

m=[{"rno":100,"studname":"hariharan","fees":10000},

{"rno":101,"studname":"geetha","fees":20000},

{"rno":102,"studname":"simran","fees":14000}] df1=pd.DataFrame(m)

print(df1) mydb =

mysql.connector.connect(host="localhost",user="root",
passwd="123456",database="IP12")

print(mydb) mycursor=mydb.cursor() mycursor.execute("show tables") for x in


mycursor:

print(x) mycursor.execute("delete from stud") mydb.commit()

for(row,rs)in df1.iterrows(): rno=str(int(rs[0])) studname=rs[1] fees=str(int(rs[2]))

mycursor.execute("insert into stud values("+rno+",'"+studname+"',"+fees+")")


print("Data exported successfully") mydb.commit()

OUTPUT:
MYSQL TABLE STUD:

CODING:

#python program to transfer the data from mysql to dataframe

import pandas as pd import mysql.connector

print("The data in the dataframe before transfer") df2=pd.DataFrame()

print(df2) mydb =

mysql.connector.connect(host="localhost",user="root",
passwd="123456",database="IP12")

print(mydb)

df2=pd.read_sql_query("select * from stud",mydb) print("Data is copied from


mysql table to dataframe successfully!!!")

print("after transfer the dataframe is:") print(df2)

mydb.commit() mydb.close()

OUTPUT:
MYSQL TABLE CONTENT:
CODING:

import pandas as pd

import matplotlib.pyplot as plt plotdata=pd.DataFrame(

{"2017":[82.0,81.5,81.8,78.5],

"2018":[83.0,71.5,92.4,88.5],

"2019":[92.0,81.9,85.8,90.5],

“2020":[98.2,89.3,92.9,99.0]},

index=["ECO","ACC","BST","IP"])

plotdata.plot(kind="bar")

plt.title("YEAR WISE - SUBJECT AVERAGE - RESULT ANALYSIS")


plt.xlabel("SUBJECTS") plt.ylabel("SUBJECT AVERAGE") plt.lengend(loc="UPPER
LEFT") plt.show()

OUTPUT:

CODING:

#program to implement multiplebarcharts import matplotlib.pyplot as plt

import pandas as pd import numpy as np


toppers=["FIRST","SECOND","THIRD"] ECO_PER=pd.Series([99,92,87])
ACC_PER=pd.Series([97,95,91]) BST_PER=pd.Series([98,90,88])

x=np.arange(len(toppers))
plt.bar(x,ECO_PER,width=0.15,color="y",label="ECONOMICS")
plt.bar(x+0.15,ACC_PER,width=0.15,color="m", label="ACCOUNTANCY")

plt.bar(x+0.30,BST_PER,width=0.15,color="g", label="BUSINESS-STUDIES")

plt.xlabel('POSITION') plt.xticks(x,toppers) plt.ylabel('PERCENTAGE %')

plt.title('MULTIPLE BAR GRAPH FOR RESULT ANALYSIS')

plt.legend() plt.show()

OUTPUT:
CODING:

#program to plot horizontal bar graph and save the graph import numpy as np

import matplotlib.pyplot as plt lang=["DOTNET","C++","JAVA","PYTHON","C","PHP"]

y_pos=np.arange(len(lang)) performance=[8,11,15,23,12,10]
plt.barh(y_pos,performance,color="cyan") plt.title("PROGRAMMING LANGUAGE
USAGE")

plt.yticks(y_pos,lang) plt.xlabel("USAGE and POPULARITY") #SAVING THE GRAPH IN


SPECIFIED LOCATION

plt.savefig("E:\Plang.jpg") plt.show()

OUTPUT:
CODING:

#program to plot a quadratic equation using dashed linechart

#equation is : 1-0.5*x**2 import matplotlib.pyplot as plt import numpy as np


xvals=np.arange(-2,1,0.01) newyval=1-0.5*xvals**2 plt.plot(xvals,newyval,"r--")

plt.title("LINE CHART - PLOTTING QUADRATIC EQUATION")

plt.xlabel("INPUT VALUES") plt.ylabel("FUNCTION VALUES") plt.show()

OUTPUT:
CODING:

#program to plot multiple line plot to visualize the spread of

#covid-19 in UAE for three months APR,MAY,JUNE,JULY 2020 import


matplotlib.pyplot as plt x=["week1","week2","week3","week4"] y1=
[101,145,189,202]

y2=[213,250,290,340] y3=[343,390,401,409] y4=[401,302,290,278]

plt.plot(x,y1,linestyle="solid",marker="d",color="red",lab el="april")
plt.plot(x,y2,linestyle="dashed",marker="s",color="blue",l abel="may")
plt.plot(x,y3,linestyle="dashdot",marker="^",color="green"

,label="june") plt.plot(x,y4,linestyle="dotted"

,marker="o",color="magenta",label="july") plt.title("MULTIPLE LINE CHART -


PLOTTING \n SPREAD OF COVID 19 in UAE")

plt.xlabel("WEEKS IN A MONTH") plt.ylabel("NUMBER OF POSITIVE CASES")

plt.legend() plt.show()

OUTPUT:
CODING:

#Program to plot histogram to visualize the frequency of #commuters in a


shopping mall

import pandas as pd
import matplotlib.pyplot as plt import random

commutes=[]

for i in range(1,101): n=random.randint(1,101) commutes.append(n)

print(commutes) plt.hist(commutes,bins=8,color='yellow',edgecolor="red")
plt.title('Commute Times for 100 Commuters') plt.xlabel('Counts')

plt.ylabel('Commute Time') plt.show()

OUTPUT:
CODING:

import matplotlib.pyplot as plt import pandas as pd

import numpy as np df=pd.read_csv("E:/edu.csv") #IMPORTING DATA FROM CSV


TO DATAFRAME

print("IMPORTING DATA FROM CSV TO DATAFRAME")

print("************************************") print("The dataframe having


the csv file data") print("") print(df)

plt.suptitle("MULTIPLE CHARTS TO VISUALIZE THE STUDENT ENROLLMENT \nIN


INDIAN GOVERNMENT SCHOOL IN DIFFERENT STATES")

plt.subplot(131) state=df["State_UT"].tolist() n=np.arange(len(state))

plt.bar(df["State_UT"],df["Higher_Secondary_Total"]) plt.xticks(n,state,rotation=90)

plt.title("STATEWISE TOTAL ENROLLMENT \nin HSEC

CLASSES",fontsize=8) plt.subplot(132)

plt.title("STATEWISE TOTAL ENROLLMENT \nin SEC

CLASSES",fontsize=8)

plt.plot(df["State_UT"],df["Secondary_Total"],marker="s",m
arkeredgecolor="blue",linestyle="solid")

plt.xticks(n,state,rotation=90)

plt.subplot(133)

plt.title("STATEWISE TOTAL ENROLLMENT \n in PRIMARY

CLASSES",fontsize=8) states=(df["State_UT"].head(6))

plt.pie(df["Primary_Total"].head(6),labels=states,autopct= "%0.1f%%")

plt.legend(loc="lower right",bbox_to_anchor=(1.3,1)) plt.show()


OUTPUT:
FIELD DATATYPE (SIZE) KEY

Student_ID int (11) Primary key

Name varchar(30)

Gender char (1)

Marks decimal(4,1)

DOB date

QUERY:

DATABASE CREATION:
TABLE CREATION:
26. To write MYSQL Queries to insert the given set of records

Student_ID Name Gender Marks DOB

1 Subhash Goyal M 91 2000/4/20

2 Nidhi Sharma F 92 2001/5/12

3 Manab Das M null 2001/1/21

4 Jyoti Baruah F 97 1998/4/12

5 George Jacob M 87 1999/7/16

6 Sunit Saha M 76 2004/11/21

7 Aman Kumar M 74 2009/1/3

8 Ankita Phukan F null 2010/2/28

9 Abhinash Lepcha M 94 2001/3/4

10 Rakhi Bandari F 99 2009/9/14

QUERY:
AFTER INSERTION – CONTENTS OF STUDENT TABLE :
a. Write a SQL query to delete the students whose marks is null

BEFORE DELETE:
DELETE QUERY:

AFTER DELETE:

a. Write a SQL query to delete the records whose student name have “I” as 4th character

BEFORE DELETE:
DELETE QUERY :

AFTER DELETE:
a. Write a SQL query to change the marks of “Manab Das “ to 82

Before UPDATE:

UPDATE QUERY:

After UPDATE:
a. Write a SQL query to change the name of “Nidhi Sharma” to “Nidhi”

BEFORE UPDATE:

UPDATE QUERY:
AFTER UPDATE:

a. Write a SQL query to display all the records


a. Write a SQL query to display the names and marks of all those students who have
secured marks above 80.

a. Write a SQL query to display roll numbers and marks of students who have secured
marks in the range 70 to 80 (including 70 and 80).

a.

a. Write a SQL query to display rows from the table Student with names starting with 'A'.

a.

a. Write a SQL query to order the (student ID, marks) table in descending order of the
marks.
a. Write a SQL query to sort all the records in descending order of StudentID and the
ascending order of DOB

a. Write a SQL query to display name and student_ID whose marks is not null
a. Write a SQL query to display name whose marks is either 87 or 76 or 94.Use(IN)

a. Write a SQL query to display unique gender

a. Write a SQL query to find the highest marks obtained by any student.

a.
a. Write a SQL query to find the lowest marks obtained by a male student.

a. Write a SQL query to find the average marks obtained by female students.

a. Write a SQL query to find the sum of marks obtained by students.

a. Write a SQL query to find the total number of male and female students in Student
table.
a. Write a SQL query to find the number of students gender wise whose count
should be greater than 5

a. Write a SQL query to find the 504.

a. Write a SQL query to round the given number to 2 decimal places .(298.348,2)
a. Write a SQL query to find the modulus value 89%5.

a. Write a SQL query to extract form from the string “INFORMATICS PRACTICES”using
substring and mid function.
a. Write a SQL query to find the position of “O” in the string “INFORMATICS PRACTICES”using
Instr function.

a. Write a SQL query to convert uppercase “BOARD EXAM” to lowercase.


a. Write a SQL query to display current date and time.

a.

a. Write SQL query to display date,month,year,dayname,monthname in a given date.

You might also like