XII Informatics Practices Practical List with Solution 2019-20 (Python - New Course)
XII Informatics Practices Practical List with Solution 2019-20 (Python - New Course)
S. No.
|
Practical Details
|
Date of Practical
|
||||||||||||||||||||||||||||||||||||||||||||||||||
Data handling using Python
libraries
|
||||||||||||||||||||||||||||||||||||||||||||||||||||
1.
|
Task: Write a
python code to create a dataframe with suitable headings from the list given
below :
[['K1',
'Mohanbari', 2019], ['K2', 'Imphal',2013], ['K3', 'Tawang', 2018]]
Python Code:
import pandas as
pd
# initialize list
of lists
data = [['K1', 'KV
Mohanbari', 2003], ['K2', 'KV Imphal',1996], ['K3', 'Tawang', 2001]]
# Create the
pandas DataFrame
df =
pd.DataFrame(data, columns = ['ID', 'KV_Name', 'Established'])
# print DataFrame.
print(df )
Output:
ID
KV_Name Established
0 K1 KV Mohanbari 2003
1 K2
KV Imphal 1996
2 K3
Tawang 2001
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
2.
|
Task: Consider
a Data Frame, where each row contains the item category, item name, and
expenditure.
·
Group the
rows by the category, and print the total expenditure per category.
Python Code:
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','Diary','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)
grpBy1 = df_Company.groupby(by='Item
Category')
print(grpBy1.sum())
Output:
Expenditure
Item Category
Diary 279.5
Marker 90.0
Notebook 300.0
Paper 620.0
Pen 20.0
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
3.
|
Task: Given a
Series, print all the elements that are above the 75th percentile.
Python Code:
import pandas as
pd
stdPercent =
[1,2,3,4,5,6,7,8,9,10]
s=pd.Series(stdPercent)
per_75=s.quantile(.75)
print("75th Percentile:",per_75)
print("List
of elements of Series that are above the 75th percentile: ")
for i in
range(len(s)):
if s[i]>=per_75:
print(s[i])
Output:
75th Percentile:
7.75
List of elements
of Series that are above the 75th percentile:
8
9
10
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
4.
|
Task: Given few details of students data, aggregate it.
Print the highest, lowest, and mean of marks obtained by students.
Python Code:
import pandas as
pd
dct =
{"AdmNo": [1,2,3,4],"Name":['Aman','Rahul',
'Saurab','Zoya'], "Class":[12,9,11,12], "Gender":['B','B','B','G'],
"Marks": [13, 13, 50, 85] }
df=
pd.DataFrame(dct, index=['A', 'B', 'C', 'D'])
print("Maximum
marks: ", df['Marks'].max())
print("Minimum
marks: ", df['Marks'].min())
print("Mean/Average
marks: ", df['Marks'].mean())
Output:
Maximum
marks: 85
Minimum
marks: 13
Mean/Average
marks: 40.25
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
5.
|
Task: Find the
Category wise sum and count of all the items using pivot_table() of pandas
library:
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','Diary','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}
Python Code:
import pandas as
pp
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','Diary','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=pp.DataFrame(data)
print(df)
pvt =
pp.pivot_table(df, index=['Item Category'], values=['Expenditure'],
aggfunc=['sum'
,'count'])
print(pvt)
Output:
Item Category Item Name Expenditure
0 Pen Ball
Point Pen 20.0
1 Marker Permanent Marker Pen 40.0
2 Marker Whiteboard Marker Pen 50.0
3 Paper A3
Paper Sheet 320.0
4 Paper A4
Paper Sheet 300.0
5 Diary Diary
Large 189.0
6 Diary Diary
Small 90.5
7 Notebook Notebook
Large- Ruled 180.0
8 Notebook Notebook
Medium- Ruled 120.0
sum count
Expenditure Expenditure
Item Category
Diary 279.5 2
Marker 90.0 2
Notebook 300.0 2
Paper 620.0 2
Pen 20.0 1
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
6.
|
Task: Write a Pandas program to select the name of
persons whose height is between 5 to 5.5 (both values inclusive)
'name': ['Asha',
'Radha', 'Kamal', 'Divy', 'Anjali'],
'height': [ 5.5,
5, np.nan, 5.9, np.nan],
'age': [11, 23,
22, 33, 22]
Python Code:
import pandas as
pd
import numpy as np
pers_data =
{'name': ['Asha', 'Radha', 'Kamal', 'Divy',
'Anjali'],
'height': [ 5.5,
5, np.nan, 5.9, np.nan],
'age': [11, 23,
22, 33, 22]}
labels = ['a',
'b', 'c', 'd', 'e']
df =
pd.DataFrame(pers_data , index=labels)
print("Persons
whose height is between 5 and 5.5")
print(df[(df['height']>=
5 )& (df['height']<= 5.5)])
Output:
Persons whose
height is between 5 and 5.5
name
height age
a Asha
5.5 11
b Radha
5.0 23
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
7.
|
Task: Write a Python program to find the total marks
obtained and percentage of marks of each student.
Python Code:
import pandas as
pd
dct =
{"SID":[1,5,7,8], "SNAME":["A", "B",
"C","D"],"MARKS1":[80,90,20,50],
"MARKS2":[80,90,20,50],
"MARKS3":[80,90,20,50]}
df=pd.DataFrame(dct)
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)
print("Percentage of ",
df.iloc[i]["SNAME"],": ", per)
print("------------------------------------------------")
Output:
Total marks obtained by A :
240
Percentage of A :
80.0
------------------------------------------------
Total marks obtained by B :
270
Percentage of B :
90.0
------------------------------------------------
Total marks obtained by C :
60
Percentage of C :
20.0
------------------------------------------------
Total marks obtained by D :
150
Percentage of D :
50.0
------------------------------------------------
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
8.
|
Task: Write Python code to perform the join, slice &
subset operations on numpy arrays.
Python Code:
import numpy as np
ar1 =
np.array([1,2,3,4,5,6,7,8])
ar2 =
np.array([7,6,5,4,3,2,1,0])
print("Slice
operation: ")
print(ar1[0:len(ar1):2])
print(ar2[3:5])
print("Subset
operation: ")
ar3, ar4=
np.split(ar1, 2)
ar5, ar6 =
np.split(ar2, 2)
print(ar3)
print(ar4)
print("Join
operation: ")
print(np.hstack((ar3,
ar4)))
print(np.vstack((ar3, ar5)))
Output:
Slice operation:
[1 3 5 7]
[4 3]
Subset operation:
[1 2 3 4]
[5 6 7 8]
Join operation:
[1 2 3 4 5 6 7 8]
[[1 2 3 4]
[7 6 5 4]]
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
9.
|
Task: Write a NumPy program to append values to the end of
an array. Expected Output:
Original array:
[10, 20, 30]
After append values to the end of the
array:
[10 20 30 40 50 60 70 80 90]
Python Code:
import numpy as np
x = [10, 20, 30]
print("Original
array:")
print(x)
x = np.append(x,
[40, 50, 60,70, 80, 90])
print("After
append values to the end of the array:")
print(x)
Output:
Original array:
[10, 20, 30]
After append values to the end of the
array:
[10 20 30 40 50 60 70 80 90]
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
10.
|
Task: Write Python program to perform the basic
arithmetic operations on ndarrays (numpy arrays).
Python Code:
import numpy as np
arr1 =
np.array([[1,2,3], [1,2,3], [7,2,3]])
arr2 =
np.array([[1,2,3], [4,5,6], [7,8,9]])
print("Array
Addition: ")
print(np.add(arr1,arr2))
print("Array
Difference: ")
print(np.subtract(arr1,arr2))
print("Array
Division: ")
print(np.divide(arr1,2))
print("Array
Multiplication: ")
print(np.multiply(arr1,arr2))
Output:
Array Addition:
[[ 2
4 6]
[ 5
7 9]
[14 10 12]]
Array Difference:
[[ 0
0 0]
[-3 -3 -3]
[ 0 -6 -6]]
Array Division:
[[0.5 1. 1.5]
[0.5 1.
1.5]
[3.5 1.
1.5]]
Array Multiplication:
[[ 1
4 9]
[ 4 10 18]
[49 16 27]]
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
11.
|
Task: Write Python code to find the Covariance and
Correlation of given data.
Python Code:
import numpy as np
data=np.array([12,13,14,15,16])
print("Covariance:
")
print(np.cov(data,ddof=0))
ar1=np.array([1,2,3,4,5,6])
ar2=np.array([11,12,3,4,5,6])
print("Correlation:
")
print(np.corrcoef(ar1,ar2))
Output:
Covariance:
2.0
Correlation:
[[ 1. -0.63906444]
[-0.63906444
1. ]]
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
12.
|
Task: Write Python code to plot bar graph of the following
set of data:
prog_lanugages = ('Python', 'C/C++',
'Java', 'Javascript', 'C#', 'PHP')
y_pos = np.arange(len(prog_lanugages))
Python Code:
import matplotlib.pyplot as plt;
import numpy as np
prog_lanugages = ('Python', 'C/C++',
'Java', 'Javascript', 'C#', 'PHP')
y_pos = np.arange(len(prog_lanugages))
use_percent = [30,6,19,8,7,6]
plt.bar(y_pos, use_percent, align='center',
alpha=0.5)
plt.xticks(y_pos, prog_lanugages)
plt.ylabel('Usage %')
plt.xlabel('Programming language')
plt.title('Programming language usage
percentage (2019)')
plt.show()
Output:
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
13.
|
Objective: To plot Histogram
Task: Write Python code to plot a Histogram of the
following data (No of Students vs. Percentage obtained ):
Roll:
[1,2,3,4,5,6,7,8,9,10,11,12]
Percent: [12,95,80,55,67,89,90,39,60,94,77,46]
Python Code:
import pandas as pd
import matplotlib.pyplot as plt
dict1 = {"Roll":[1,2,3,4,5,6,7,8,9,10,11,12],
"Percent":[12,95,80,55,67,89,90,39,60,94,77,46]}
df = pd.DataFrame(dict1)
df1 =
df["Percent"].sort_values()
plt.hist(df1,
bins=[0,10,20,30,40,50,65,70,80,90,100],edgecolor='red')
plt.yticks(range(0,6))
plt.xlabel("Percentage
Range")
plt.ylabel("No of Students")
plt.title('Result Analysis- XII KVC')
plt.show()
Output:
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
14.
|
Task: Write a NumPy program to create a 3x3 identity
matrix, i.e. diagonal elements are 1, the rest are 0. Replace all 0 to random
number from 10 to
20.
Python Code:
import numpy as np
array1=np.identity(3)
print("Identitry
Matrix: ")
print(array1)
x=np.where(array1==0)
for i in x:
array1[x]=np.random.randint(low=10,high=20)
print("Matrix
after replacement: ")
print(array1)
Output:
Identitry Matrix:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Matrix after replacement:
[[ 1. 15. 15.]
[15.
1. 15.]
[15. 15.
1.]]
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
15.
|
Task: Write Python code to draw a Box plot of the
following data:
IP_Marks = [79,
99,75,35,89,76,100,59,14]
Python Code:
import
matplotlib.pyplot as plt
IP_Marks = [79,
99,75,35,89,76,100,59,14]
plt.boxplot(IP_Marks)
plt.ylabel("Marks
Obtained")
plt.title("IP
MARKS - Box Plot")
plt.show()
Output:
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
16.
|
Task: Write Python code to draw a Scatter plot of the
following data:
x_Ball =
[1,2,3,4,5,6]
y_Run =
[3,1,0,4,6,4]
Python Code:
import
matplotlib.pyplot as plt
x_Ball =
[1,2,3,4,5,6]
y_Run =
[3,1,0,4,6,4]
plt.scatter(x_Ball,
y_Run)
plt.xlabel("Ball
No.")
plt.ylabel("Runs
Scored")
plt.title("Over
Details")
plt.show()
Output:
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
Data Management: SQL + web-server
|
||||||||||||||||||||||||||||||||||||||||||||||||||||
17.
|
Objective: Understanding of SQL Commands & SQL Aggregate
function.
Task A: Write SQL query to Create a table Student with
following details:
SQL Query: CREATE
TABLE Student (Studentid INT(11), Name VARCHAR(30), Gender CHAR(1), Marks DECIMAL(4,1));
Table: Student
Task B: Write a SQL query to insert the first record
in the Student table.
SQL Query: INSERT INTO Student VALUES (1, ‘Subhash Goyal’,
‘M’,91);
Task C: Write a SQL query to display the names and marks of
all those students who have secured marks above 80.
SQL Query: SELECT Name, Marks FROM Student WHERE Marks > 80;
Task D: 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).
SQL Query: SELECT Rollno, Name, Marks FROM Student WHERE Marks
BETWEEN 70 AND 80;
Task E: Write a SQL query to display rows from the table
Student with names starting with 'A'.
SQL Query: SELECT * FROM Student WHERE Name LIKE 'A%';
Task F: Write a SQL query to order the (student ID, marks)
table in descending order of the marks.
SQL Query: SELECT StudentID, Marks from Student ORDER BY Marks
DESC;
Task G: Write a SQL query to change the marks
of ‘Manab Das’ from 99 to 100.
SQL Query: UPDATE Student SET Marks = 100 WHERE Name
=’Manab Das’;
Task H: Write a SQL query to find the highest marks obtained
by any student.
SQL Query: SELECT MAX(Marks) FROM Student;
Task I: Write a SQL query to find the lowest marks obtained
by a male student.
SQL Query: SELECT MIN(Marks) FROM Student WHERE Gender = ‘M’;
Task J: Write a SQL query to find the average marks obtained
by female students.
SQL Query: SELECT AVG(Marks) FROM Student WHERE Gender = ‘F’;
Task K: Write a SQL query to find the sum of marks obtained
by students.
SQL Query: SELECT SUM(Marks) FROM Student;
Task L: Write a SQL query to find the total number of male
and female students in Student table.
SQL Query: SELECT COUNT(*) FROM Student GROUP BY Gender;
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
18.
|
Task: Write a Python program to create a database “KVS” to
show the integration of SQL with Python by importing MYSQL DB. Also list all
the databases using Python code.
Python Code:
import mysql.connector as sql
con = sql.connect(host="localhost",
user="root", passwd="tiger")
curs = con.cursor()
query ="CREATE DATABASE
KVS;"
print("Database created.")
print("List of Databases: ")
query1 = "SHOW DATABASES;"
curs.execute(query1)
for i in curs:
print(i)
Output:
Database created.
List of Databases:
('information_schema',)
('kvs',)
('mysql',)
('test',)
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
19.
|
Task: Write a Python program to create a Table “Student”
to show the integration of SQL with Python by importing MYSQL DB. Details of
columns of tables:
Python Code:
import
mysql.connector as sql
con =
sql.connect(host="localhost", user="root",
passwd="tiger", database="kvs")
curs =
con.cursor()
query
="CREATE TABLE Student (Roll int, Name varchar(30), Gender char(1),
Class int);"
print("Table
created.")
curs.execute(query)
print("List
of Tables: ")
query1 =
"SHOW TABLES;"
curs.execute(query1)
for i in curs:
print(i)
Output:
Table created.
List of Tables:
('student',)
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
20.
|
Task: Write a Python program to insert following records
in table “Student” to show the integration of SQL with Python by importing
MYSQL DB:
Python code:
import
mysql.connector as sql
con = sql.connect(host="localhost",
user="root", passwd="tiger", database="kvs")
curs =
con.cursor()
query
="INSERT INTO Student VALUES(1, 'AMAN YADAV', 'M', 12);"
curs.execute(query)
query1
="INSERT INTO Student VALUES(2, 'SIDDHI BARUAH', 'F', 12);"
curs.execute(query1)
con.commit()
print("Record
inserted.")
Output:
Record inserted.
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
21.
|
Task: Write a Python program to display all records of
table “Student” to show the integration of SQL with Python by importing MYSQL
DB.
Python Code:
import mysql.connector as sql
con =
sql.connect(host="localhost", user="root",
passwd="tiger", database="kvs")
curs = con.cursor()
query ="SELECT * FROM
Student;"
curs.execute(query)
records = curs.fetchall()
for i in records:
print (i)
Output:
(1, 'AMAN YADAV', 'M', 12)
(2, 'SIDDHI BARUAH', 'F', 12)
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||
22.
|
Task: Write a Django based web server to parse a user
request (POST), and write it to a CSV file.
Python Code:
Output:
|
|