0% found this document useful (0 votes)
2 views

XII IP PRACTICAL LIST 2022-23-1

The document outlines a practical list for Class XII Informatics Practices at Kendriya Vidyalaya Ambarnath for the session 2023-24. It includes various tasks related to data manipulation using Pandas, such as creating series and dataframes, filtering data, and performing operations like transposing data and handling duplicates. Additionally, it covers visualization techniques using Matplotlib and SQL queries for database operations.

Uploaded by

28kpclasses
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)
2 views

XII IP PRACTICAL LIST 2022-23-1

The document outlines a practical list for Class XII Informatics Practices at Kendriya Vidyalaya Ambarnath for the session 2023-24. It includes various tasks related to data manipulation using Pandas, such as creating series and dataframes, filtering data, and performing operations like transposing data and handling duplicates. Additionally, it covers visualization techniques using Matplotlib and SQL queries for database operations.

Uploaded by

28kpclasses
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/ 23

KENDRIYA VIDYALAYA AMBARNATH

PRACTICAL LIST
CLASS: XII
SUB: INFORMATIC PRACTICES
SESSION:2023-24

SERIES AND DATAFRAMES


1. Create a pandas series from a dictionary of values and an
ndarray.
import pandas as pd
import numpy as np
s=pd.Series(np.array([1,3,4,7,8,8,9]))
print(s)
# create a dictionary
dictionary = {'X' : 10, 'Y' : 20, 'Z' : 30} # create a series
series = pd.Series(dictionary)
print(series)
2. Write a Pandas program to select the rows where the
percentage greater than 70.

import pandas as pd
import numpy as np
exam_data = {'name': ['Aman', 'Kamal', 'Amjad', 'Rohan', 'Amit',
'Sumit', 'Matthew', 'Kartik', 'Kavita', 'Pooja'],
'perc': [79.5, 29, 90.5, np.nan, 32, 65, 56, np.nan, 29, 89],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no',
'yes']}
labels = ['A', 'B', 'C', 'B', 'E', 'F', 'G', 'H', 'I', 'J']
df = pd.DataFrame(exam_data , index=labels)
print("Number of student whoes percentage more than 70:")
print(df[df['perc'] > 70])
3. Filter out rows based on different criteria such as duplicate rows.

import pandas as pd
data={'Name':['Aman','Rohit','Deepika','Aman','Deepika',
'Sohit','Geeta'],
'Sales':[8500,4500,9200,8500,9200,9600,8400]}
sales=pd.DataFrame(data)
# Find duplicate rows
duplicated = sales[sales.duplicated(keep=False)]
print("duplicate Row:\n",duplicated)

4. Create a data frame for examination results and display row


labels, column labels data types of each column and the
dimensions.
import pandas as pd
res={'Amit':[76,78,75,66,68],
'Shialesh':[78,56,77,49,55],
'Rani':[90,91,93,97,99],
'Madan':[55,48,59,60,66],
'Radhika':[78,79,85,88,86]}
df=pd.DataFrame(res)
print("Prinitng row labels in a list:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
idx=df.index
l=list(idx)
print(l)
print("Prinitng row labels in a list:")
rint("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("[",end=" ")
For col in df.columns:
print(col,end=" ")
print("]")
print("PrintingDataTypesofeachcolumn")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(df.dtypes)
print("PrintingdimensionsofDataFrame")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(df.ndim)
5. Create the following DataFrame Sales containing year wise sales
figures for five salespersons in INR. Use the years as column
labels, and salesperson names as row labels.
2018 2019 2020 2021
Kapil 110 205 177 189
Kamini 130 165 175 190
Shikhar 115 206 157 179
Mohini 118 198 183 169
1. Create the DataFrame.
2. Display the row labels of Sales.
3. Display the column labels of Sales.
4. Display the data types of each column of Sales.
5. Display the dimensions, shape, size and values of Sales.
import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini
'])
#Display row lables
print("Row Lables:\n",sales.index)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
#Display column lables
print("Column Lables:\n",sales.columns)
print("~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
#Display data type
print("\nDisplay column data types")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(sales.dtypes)
print("\nDisplay the dimensions, shape, size and values of Sales")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Dimensions:",sales.ndim)
print("Shape:",sales.shape)
print("Size:",sales.size)
print("Values:",sales.values)
6 . Use above dataframe and do the following:
1. Change the DataFrame Sales such that it becomes its transpose.
2. Display the sales made by all sales persons in the year 2018.
3. Display the sales made by Kapil and Mohini in the year 2019 and
2020.
4. Add data to Sales for salesman Nirali where the sales made are
● [221, 178, 165, 177, 210] in the years [2018, 2019, 2020, 2021]
respectively
5. Delete the data for the year 2018 from the DataFrame Sales.
6. Delete the data for sales man Shikhar from the DataFrame Sales.
7. Change the name of the salesperson Kamini to Rani and Kapil to
Anil.
8. Update the sale made by Mohini in 118 to 150 in 2018.
Solution:
import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
print("Transpose:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(sales.T)
print("\nSales made by each salesman in 2018")

#Method 1
print(sales[2018])

#Method 2
print(sales.loc[:,2018])

print("Sales made by Kapil and Mohini:")


#Method 1
print(sales.loc[['Kapil','Mohini'], [2019,2020]])

#Method 2
print(sales.loc[sales.index.isin(["Kapil","Mohini"]),[2019,2020]])

print("Add Data:")
sales.loc["Nirali"]=[221, 178, 165, 177]
print(sales)

print("Delete Data for 2018:")


sales=sales.drop(columns=2018)
print(sales)

Sales.drop(columns=2018,inplace=True)
print(Sales)

sales=sales.drop("Shikhar",axis=0)
#sales.drop("kinshuk")
print(sales)
sales=sales.rename({"Kamini":"Rani","Kapil":"Anil"},axis="index")
print(sales)

sales.loc[sales.index=="Mohini",2018]=150
print(sales)

7.Create a Data Frame quarterly sale where each row contains the
item category, item name, and expenditure. Group the rows by the
category, and print the total expenditure per category.
import pandas as pd

# initialize list of lists


data=[['CAR','Maruti',1000000],
['AC','Hitachi',55000],
['AIRCOLLER','Bajaj',12000], ['WASHINGMACHINE','LG',15000],
['CAR','Ford',7000000],['AC','SAMSUNG',45000],
['AIRCOLLER','Symphony',20000],
['WASHING MACHINE','Wirlpool',25000]]

Col=['itemcat','itemname','expenditure']
# Create the pandas DataFrame

qrtsales = pd.DataFrame(data,columns=Col)

# print dataframe.
print (qrtsales)

qs=qrtsales.groupby('itemcat')
print('Result after Filtering Dataframe')
print(qs['itemcat','expenditure'].sum())
8.Write a Pandas program to count the number of rows and columns of a
Data Frame.

import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James',
'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'], 'score': [12.5, 9,
16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19], 'attempts': [1, 3, 2, 3, 2, 3, 1,
1, 2, 1], 'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels) t
total_rows=len(df.axes[0])
total_cols=len(df.axes[1])
print("Number of Rows: "+str(total_rows))
print("Number of Columns: "+str(total_cols))

9.Consider above dataframe and write code to do the following:


1. Display the last two rows of Sales.
2. Display the first two columns of Sales.
import pandas as pd
#Creating DataFrame
d = {2018:[110,130,115,118],
2019:[205,165,175,190],
2020:[115,206,157,179],
2021:[118,198,183,169]}
sales=pd.DataFrame(d,index=['Kapil','Kamini','Shikhar','Mohini'])
print("Display last two rows of DataFrame:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")

#Method 1
print("Using tail function:")
print(Sales.tail(2))

#Method 2
print("Using iloc")
print(Sales.iloc[-2:])

#With Specific Columns, I have prnted two columns


print("Sepcific Columns")
print(Sales.iloc[-2:,-2:])
10.Read the ‘Student_result.csv’ to create data frame and do the
following operation:

▪ To display Student_result file with new column names.

▪ To modify the Percentage of student below 40 with

NaN value in dataframe.

import pandas as pd
import numpy as np
import csv

df = pd.read_csv("student_result.csv")
print(df)

#To display Student_result file with new column names.


df1 = pd.read_csv("student_result.csv",skiprows = 1,
names = ['Adno','Sex','Name','Eng','Hin',
'Maths','Sc.','SSt','San','IT','Perc'])

print("To display Student_result file with new column names")


print(df1)

# To modify the Percentage of student below 40 with NaN value.


df2 = pd.read_csv("student_result.csv")
print(df2)

print("To modify the Percentage of student below 40 with NaN


value.")
df2.loc[(df2['PERCENTAGE'] <40, 'PERCENTAGE')] = np.nan
print(df2)
Visualization

11. Given the school result data, analyses the performance of the students
on different parameters, e.g subject wise or class wise.
import pandas as pd
import matplotlib.pyplot as plt
subject = ['Physic','Chemistry','Mathematics', 'Biology','Computer']
marks =[80,75,70,78]
plt.plot(subject,marks,'green',marker ='*') # To draw line in red
colour
plt.title('Marks Scored') # To Write Title of the Line Chart
plt.xlabel('SUBJECT') # To Put Label At Y Axis
plt.ylabel('MARKS') # To Put Label At X Axis
plt.show()

12. Write a program to plot a bar chart in python to display the result of
a school for five consecutive years.
import matplotlib.pyplot as pl
year=['2015','2016','2017','2018','2019'] # list of years
p=[98.50,70.25,55.20,90.5,61.50] #list of pass percentage
j=['b','g','r','m','c'] # color code of bar charts
pl.bar(year, p, width=0.2, color=j)
pl.xlabel("year") # label for x-axis
pl.ylabel("Pass%") # label for y-axis
pl.show( ) # function to display bar chart
13. Plot the following data on a line chart and customize
the chart according to the below-given instructions:

Month January February March April May


Sales 510 350 475 580 600
Weekly Sales Report
Write a title for the chart “The Monthly Sales Report“
1. Write the appropriate titles of both the axes
2. Write code to Display legends
3. Display blue color for the line
4. Use the line style – dashed
5. Display diamond style markers on data points
import matplotlib.pyplot as pp
mon =['January','February','March','April','May']
sales = [510,350,475,580,600]
pp.plot(mon,sales,label='Sales',color='b',linestyle='dashed',marke
r='D')
pp.title("The Monthly Sales Report")
pp.xlabel("Months")
pp.ylabel("Sales")
pp.legend()
pp.show()

14. Write a program to plot a range from 1 to 30 with step value 4. Use
following algebraic expression to show data.
y = 5*x+2
import matplotlib.pyplot as pp
import numpy as np
x = np.arange(1,30,4)
y=5*x+2
pp.plot(x,y)
pp.show()
15. Write python code to accept data of students and draw bar
chart.

import matplotlib.pyplot as pl

while(1):
print(" MENU")
print("1. Enter the data")
print("2. Plot the graph")
print("3. Exit")
ch=int(input("Enter the choice"))
if(ch==1):
n=int(input("Enter the number of students :"))
name=[]
mark=[]
for i in range(n):
n=input("Enter the name of the student :")
m=int(input("Enter the total marks :"))
name.append(n)
mark.append(m)
print(name)
print(mark)
elif(ch==2):
pl.bar(name,mark)
pl.grid()
pl.xlabel("Name")
pl.ylabel("Mark")
pl.title("Marks of student ")
pl.show()
elif(ch==3):
break
else:
print("Wrong choice")
SQL QUERIES

Queries Set 1 (Database Fetching records)


[1] Consider the following MOVIE table and write the SQL queries based on
it.

1. Display all information from the movie.


2. Display the type of movies.
3. Display movieid, movie name, total_eraning by showing the
business done by the movies. Calculate the business done by
movie using the sum of production cost and business cost.
4. Display movie id, movie name and production cost for all movies
with production cost greater than 150000 and less than 1000000.
5. Display the movie of type action and romance.
6. Display the list of movies which are going to release in February,
2022.

Answers:
[1] select * from movie ;
Output:
2. select distinct from a movie ;

3. select movieid, movie name, production cost + business cost “total


earning” from movie ;

4. select movie_id, movie name, production cost from movie where product
is >150000 and <1000000 ;
5. select movie name from movie where type =’action’ or type=’romance’ ;

6. select movie name from movie where month(release date)=2 ;

Queries Set 2 (Based on Functions)

1. Write a query to display a cube of 5.


2. Write a query to display the number 563.854741 rounding off to the
next hundred.
3. Write a query to display “put” from the word “Computer”.
4. Write a query to display today’s date into DD.MM.YYYY format.
5. Write a query to display ‘DIA’ from the word “MEDIA”.
6. Write a query to display movie name – type from the table movie.
7. Write a query to display the first four digits of production cost.
8. Write a query to display the last four digits of business cost.
9. Write a query to display weekdays of release dates.
10. Write a query to display the dayname on which movies are
going to be released.

Answers:
[1] select pow(5,3) ;

[2] select round(563.854741,-2) ;

[3] select mid(“Computer”,4,3) ;


[4] select
concat(day(now()),concat(‘.’,month(now()),concat(‘.’,year(now())))) “Date” ;

[5] select right(“Media”,3) ;

[6] select concat(movie name,concat(‘ – ‘,type)) from movie ;

[7] select left (production cost,4) from movie ;


[8] select right (business cost,4) from movie ;

[9] select weekday (release date) from movie ;

[10] select dayname (release date) from movie ;

Queries Set 3 (DDL Commands)


Suppose your school management has decided to conduct cricket matches
between students of Class XI and Class XII. Students of each class are
asked to join any one of the four teams – Team Titan, Team Rockers, Team
Magnet and Team Hurricane. During summer vacations, various matches
will be conducted between these teams. Help your sports teacher to do the
following:
1. Create a database “Sports”.
2. Create a table “TEAM” with following considerations:
o It should have a column TeamID for storing an integer
value between 1 to 9, which refers to unique identification
of a team.
o Each TeamID should have its associated name
(TeamName), which should be a string of length not less
than 10 characters.
o Using table level constraint, make TeamID as the primary
key.
o Show the structure of the table TEAM using a SQL
statement.
o As per the preferences of the students four teams were
formed as given below. Insert these four rows in TEAM
table:
▪ Row 1: (1, Tehlka)

▪ Row 2: (2, Toofan)

▪ Row 3: (3, Aandhi)

▪ Row 3: (4, Shailab)


o Show the contents of the table TEAM using a DML
statement.
3. Now create another table MATCH_DETAILS and insert data as
shown below. Choose appropriate data types and constraints for
each attribute.

Match MatchD FirstTea SecondTea FirstTeamS SecondTeam


ID ate mID mID core Score

M1 2021/12 1 2 107 93
/20

M2 2021/12 3 4 156 158


/21

M3 2021/12 1 3 86 81
/22

M4 2021/12 2 4 65 67
/23

M5 2021/12 1 4 52 88
/24

M6 2021/12 2 3 97 68
/25

Answers:
[1] create database sports
[2] Creating table with the given specification

create table team


-> (teamid int(1),
-> teamname varchar(10), primary key(teamid));

Showing the structure of table using SQL statement:

desc team;

Inserting data:

mqsql> insert into team


-> values(1,'Tehlka');
Show the content of table – team:

select * from team;

Creating another table:

create table match_details


-> (matchid varchar(2) primary key,
-> matchdate date,
-> firstteamid int(1) references team(teamid),
-> secondteamid int(1) references team(teamid),
-> firstteamscore int(3),
-> secondteamscore int(3));
Queries Set 4 (Group by , Order By)
Consider the following table stock table to answer the queries:

item item dcod qty unit stockdate


no e price

S005 Ballpen 102 10 10 2018/04/2


0 2

S003 Gel Pen 101 15 15 2018/03/1


0 8

S002 Pencil 102 12 5 2018/02/2


5 5

S006 Eraser 101 20 3 2018/01/1


0 2

S001 Sharpner 103 21 5 2018/06/11


0

S004 Compass 102 60 35 2018/05/1


0

S009 A4 102 16 5 2018/07/1


Papers 0 7

1. Display all the items in the ascending order of stockdate.


2. Display maximum price of items for each dealer individually as per
dcode from stock.
3. Display all the items in descending orders of item names.
4. Display average price of items for each dealer individually as per
doce from stock which average price is more than 5.
5. Display the sum of quantity for each dcode.
[1] select * from stock order by stockdale;

[2] select dcode,max(unit price) from stock group by code;

[3] select * from stock order by item desc;


[4] select dcode,avg(unit price) from stock group by dcode having avg(unit
price)>5;

[5] select dcode,sum(qty) from stock group by dcode;

You might also like