You are on page 1of 15

GYANODAYA INTERNATIONAL SCHOOL

PRACTICAL FILE CLASS XII 2022-23


#Python Pandas
1) Write a program to generate a series with the help of list and dictionary having values as
10,20,30,40,50 and index as a,b,c,d,e.
#Solution
import pandas as pd
#Creating series with the help of list
lst=[10,20,30,40,50]
ind=[„a‟,‟b‟,‟c‟,‟d‟,‟e‟]
s = pd.Series(lst,ind)
print(s)
# creating series with the help of dictionary
d={„a‟:10,‟b‟:20,‟c‟:30,‟d‟:40,‟e‟:50}
s=pd.Series(d)
print(s)

2) Create a series of these numbers: 33,55,65,29,19,23. Find the sum of those values which
are ending with 3 or 5.
#Solution
import pandas as pd
list=[33,55,65,29,19,23]
ser=pd.Series(list)
sumall=0
sum5=sum(ser[ser%10==5])
sum3=sum(ser[ser%10==3])

sumall=sum5+sum3
print(“Sum=”,sumall)

3) Write a program to generate a series of 10 numbers with a scalar value of 44.


#Solution
import pandas as pd
S=pd.Series(44,range(1,11))
print(S)
4) Create a series of 10 numbers starting with 41 and with the increment of 3. Now add 7 to all odd
values and subtract 3 in even values. Reprint the updated series.

import pandas as pd
ser=pd.Series(range(41,71,3))
for i in range(0,ser.size):
if (ser[i]%2==0):
ser[i]=ser[i]-3

else:
ser[i]=ser[i]+7
print(ser)

5) Create a series and print the top 3 elements using the head function and bottom 4 element using tail
function
#Solution
import pandas as pd
ser=pd.Series(range(3,71,7))
print("Top 3 Elements are ")
print(ser.head(3))
print("Bottom 4 Elements are ")
print(ser.tail(4))

6) Create a panda’s series from a dictionary of values and a ndarray.


#Solution
import pandas as pd
import numpy as np
#Creating series from a dictionary
d={'Jan':31,'Feb':28,'Mar':31,'Apr':30}
s=pd.Series(d)
print("Series from dictionary")
print(s)
#Creating series from an ndarray
ar=np.array([2,3,4,5,6])
print("\nSeries from ndarray")
s1=pd.Series(ar)
print(s1)
7) Create two series S1 and S2 using range function to perform variousmathematical 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

8) Given a Series, print all the elements that are above the 75th percentile.
#Solution
import pandas as pd
lst=[10,20,30,45,75,63,72,78]
s=pd.Series(lst)
print(s[s>s.quantile(.75)])
9) Create a data frame for examination results and display row labels, column labels, data types of each
column and the dimensions.
#Solution
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:")

idx=df.index
print(idx)
print("Prinitng row labels in a list:")
for col in df.columns:
print(col,end=" ")
print("Printing Data Types of each column")
print(df.dtypes)
print("Printing dimensions of Data Frame")
print(df.ndim)

8) Create a dataframe players using a list of names and scores of the previous three
matches. (Using Nested list)
import pandas as pd
data=[["Virat",56,66,31],["Rohit",88,66,43],["Dhoni",75,54,56]]
players=pd.DataFrame(data,columns=["Name","M1","M2","M3"])
print(players)

10) Create a dataframe and iterate them over rows.


#Solution
import pandas as pd
data = [["Virat",55,66,31],["Rohit",88,66,43],[ "Hardik",99,101,68]]
players = pd.DataFrame(data, columns = ["Name","Match-1","Match-2","Match-3"])
print("Iterating by rows:")
for index, row in players.iterrows():
print(index, row.values)
print("Iterating by columns:")
for index, row in players.iterrows():
print(index, row)
11) Write a Python program to create a DataFrame as given below, anddisplay 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
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)
print(df)
print("Index=",df.index)
print("columns=",df.columns)
print(df.shape)
print("Size : ",df.size)
print("Axes :",df.axes)
print("Rows :",df.values)
print("Columns :",df.columns)
12) Write a python program to do the following to the dataframe:-
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
a. Create the above dataframe
b. Add a column name class and insert 12 in all of the rows
c. Rename the name column as Student_Name.
d. Drop the column class
e. Use loc and iloc function to access 3rd to 5th row and name and percentage column
f. Update the name value of RollNo 10E12 to Mukesh using at and iat function
#Solution
# Creating the above dataframe.
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)
print(df)
# Adding column name class
df[„class‟]=12
# Renaming the column
df.rename(columns={„Name‟:”Student_Name”},inplace=True)
# Dropping the column class
df.drop(„class‟,axis=1)
# Using loc and iloc
df.loc[2:4,[„Name‟,‟Percentage‟]]
df.iloc[2:5,[1,3]]
# Updating using at and iat
df.at[2,‟Name‟]=”Mukesh”
df.iat[2,1]=”Mukesh”
13) Create a dataframe named cricket having score given in odi, test and T20 matches. Display the
batsman details who scored
a. More than 2000 in ODI
b. Less than 2500 in Test
c. More than 1500 in T20
#Solution
import pandas as pd
data={"Name":["Virat","Rohit","Dhoni","Yuvraj"],
"Test":[3543,2578,2280,3625],
"ODI":[2845,2665,2580,2280],
"T20":[1925,1586,1890,1635]}
cricket=pd.DataFrame(data)
#run more tahn 2500 in ODI
print(cricket.loc[cricket["ODI"]>2500,["Name"]])
#run more than 2000 in T20
print(cricket.loc[cricket["T20"]>2000,["Name"]])
#run more than 2200 in Test
print(cricket.loc[cricket["Test"]>2200,["Name"]])

14) Write a python program to import data from a csv file and after adding a column to it write again to
the csv file.
import pandas as pd
print(“Importing data from csv file”)
df=pd.read_csv(“d:\\sample.csv”,header=None,names=[„RN‟,‟Name‟,‟Class‟],nrows=10)
print(df)
df[„city‟]=”Neemuch”
print(“DataFrame after column addition”)
print(df)
df.to_csv(“d:\\sample.csv”,sep=”;”,na_rep=”NULL”)
print(“Data Written to CSV file successfully”)
15) Write a python program to import data from mysql table into dataframe using sqlalchemy.
#Solution
import pandas as pd
import sqlalchemy as sq
import pymysql
engine=sq.create_engine(“mysql+pymsql://root:root123@localhost/cbse’)
con=engine.connect()
df=pd.read_sql(“Select *from Student”,con)
print(df)

#MATPLOTLIB

16) 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

1. Weekly Sales Report


2. Write a title for the chart “The Monthly Sales Report“
3. Write the appropriate titles of both the axes
4. Write code to Display legends
5. Display blue color for the line
6. Use the line style – dashed
7. Display diamond style markers on data points
#Solution
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',marker='D')
pp.title("The Monthly Sales Report")
pp.xlabel("Months")
pp.ylabel("Sales")
pp.legend()
pp.show()
17) Pratyush Garments has recorded the following data into their register for their income from cotton
clothes and jeans. Plot them on the line chart.
Day Monday Tuesday Wednesday Thursday Friday

Cotton 450 560 400 605 580

Jeans 490 600 425 610 625


Apply following customization to the line chart.
1. Write a title for the chart “The Weekly Garment Orders”.
2. Write the appropriate titles of both the axes.
3. Write code to Display legends.
4. Display your choice of colors for both the lines cotton and jeans.
5. Use the line style – dotted for cotton and dashdot for jeans.
6. Display plus markers on cotton and x markers of jeans.

#Solution
import matplotlib.pyplot as pp
day =['Monday','Tuesday','Wednesday','Thursday','Friday']
ct = [450,560,400,605,580] js = [490,600,425,610,625]
pp.plot(day,ct,label='Cotton',color='g',linestyle='dotted',marker='+')
pp.plot(day,js,label='Food',color='m',linestyle='dashdot',marker='x')
pp.title("The Weekly Garment Orders")
pp.xlabel("Days")
pp.ylabel("Orders")
pp.legend()
pp.show()
18) Observe the given data for monthly views of one of the youtube channels for 6 months. Plot them on
the line chart.
Month January February March April May June

Views 2500 2100 1700 3500 3000 3800


Apply the following customizations to the chart:
1. Give the title for the chart – “Youtube Stats”
2. Use the “Month” label for X-Axis and “Views” for Y-Axis.
3. Display legends.
4. Use width=.5 for all the bars.
5. Use different colors for all the bars.

#Solution

import matplotlib.pyplot as pp
mon =['January','February','March','April','May','June']
views = [2500,2100,1700,3500,3000,3800]
pp.bar(mon,views,width=.5,color=[„r‟,‟g‟,‟b‟,‟c‟,‟m‟,‟y‟])
pp.title("Youtube Stats")
pp.xlabel("Months")
pp.ylabel("Views")
pp.legend()

19) Draw to bar chart showing the comparison of two teams score in 5 overs, giving the proper title ,
xlabel , ylabel and legend.
#Solution
import matplotlib.pyplot as pt
import numpy as np
overs=np.array([1,2,3,4,5])
team1=[3,8,4,6,5]
team2=[6,2,9,5,3]
pt.bar(overs,team1,width=.3,color=‟g‟,label=”Team A”)
pt.bar(overs+.3,team2,width=.3,color=‟r‟,label=”Team B”)
pt.legend()
pt.xlabel(“Overs”)
pt.ylabel(“Runs”)
pt.title(“Run rate comparision”)
pt.show()
20) Create a histogram from the data given for the students in class XII,
#Solution
import matplotlib.pyplot as pt
x=[23,54,76,90,59,87,67,49,93]
pt.hist(x,bins=[0,33,50,80,100]
pt.title(“Histogram for showing the distribution of Marks of Student”)
pt.xlable(“Marks Range”)
pt.ylabel(“No. of Student Scored”)
pt.show()
MYSQL/SQL QUERIES
1. Create a database with name CBSE.
Ans) CREATE DATABASE CBSE.
2. Display all the databases available in your system.
Ans) SHOW DATABASES;
3. Select the database cbse which is created in the above query.
Ans) USE CBSE;
4. Create a student table with the student id, name, and marks as attributes where the student id is the
primary key.
Ans) CREATE TABLE STUDENT(ID INT PRIMARY KEY, NAME CHAR(30), MARKS INT NOT NULL);
5. Insert the details of a new student in the above table.
Ans) INSERT INTO STUDENT VALUES(101,’AMAN’,96);
INSERT INTO STUDENT VALUES(102,’SOHAN’,86);
INSERT INTO STUDENT VALUES(103,’ROHAN’,72);
INSERT INTO STUDENT VALUES(104,’KARAN’,81);
INSERT INTO STUDENT VALUES(105,’MUKESH’,66);
INSERT INTO STUDENT VALUES(106,’BALKISHAN’,70);
6. Delete the details of a student in the above table.
Ans) DELETE FROM STUDENT WHERE RN=102;
DELETE FROM STUDENT WHERE NAME=’KARAN’;
7. Use the select command to get the details of the students with marks more than 80.
Ans) SELECT *FROM STUDENT WHERE MARK>80;
8. Find the min, max, sum, and average of the marks in a student marks table.
Ans) SELECT MIN(MARKS),MAX(MARKS),SUM(MARKS),AVG(MARKS) FROM STUDENT;
9. Consider a table with name customer having attributes as (customer ID, customer
Name, country) Find the total number of customers from each country in the table.
Ans) SELECT COUNTRY,COUNT(CUSTOMER_NAME) FROM CUSTOMER GROUP BY COUNTRY;
10. Write a SQL query to order the (student ID, marks) table in descending order of the marks.
Ans) SELECT * FROM STUDENT ORDER BY STUDENT_ID DESC, MARKS DESC;
11. Write a SQL query to display the marks without decimal places, display the reminder after diving marks by
3 and display the square of marks.
Ans) SELECT ROUND(MARKS),MOD(MARKS,3),POWER(MARKS,2) FROM STUDENT;
12. Write a SQL query to display names into capital letters, small letters, display frist 3 letters of name, display
last 3 letters of name, display the position the letter A in name.
Ans) SELECT UPPER(NAME), LOWER(NAME), LEFT(NAME,3), RIGHT(NAME,3),INSTR(NAME,’A’) FROM
STUDENT
13. Remove extra spaces from left, right and both sidesfrom the text – ” Informatics Practices Class XII “.
Ans) SELECT LTRIM(” Informatics Practices Class XII “);
SELECT RTRIM(” Informatics Practices Class XII “);
SELECT TRIM(” Informatics Practices Class XII “);
14. Display today’s date in “Date/Month/Year” format.
Ans) SELECT date_format(now( ), ‘%d/%m/%Y’);
15. Display dayname, monthname, day, day of week for today’s date.
Ans) SELECT DAYNAME(NOW( ));
SELECT MONTHNAME(NOW ( ));
SELECT DAY(NOW( ));
SELECT DAYOFWEEK(NOW ( ));
16. Create following table: EMP,
Ans) CREATE TABLE Employee (EID INT PRIMARY KEY, NAME VARCHAR(20), DEPT VARCHAR(20), GEN
CHAR(1), SALARY DECIMAL(10,2), DOJ DATE);
17. Insert Some records into the employee table as per your choice-
 INSERT INTO Employee VALUES (1,'RASHI','COMPUTER','F',185000.00,'2010-01- 01');
 INSERT INTO Employee VALUES (2,'RISHIKA','ACCOUNTS','F',115000.00,'2015-07- 01');
 INSERT INTO Employee VALUES ( 3,'AKSHIT','SALES','M',125000.00,'2015-07- 01');
 INSERT INTO Employee VALUES (4,'MOHIT','SALES','M',105000.00,'2015-01- 15');
 INSERT INTO Employee VALUES (5,'TAPPU','ACCOUNTS','M',55000.00,'2015-01- 27');
 INSERT INTO Employee VALUES (6,'SAHIL','COMPUTER','M',125000.00,'2018-07-02');
18. Show all data of table
Ans) Select *from employee;
EID NAME DEPT GEN SALARY DOJ
1 RASHI COMPUTER F 185000 01/01/2010
2 RISHIKA ACCOUNTS F 115000 01/07/2015
3 AKSHIT SALES M 125000 01/07/2015
4 MOHIT SALES M 105000 15/01/2015
5 TAPPU ACCOUNTS M 550000 27/01/2015
6 SAHIL COMPUTER M 125000 02/07/2018

19. Write SQL query :


19.1 Show number of employee gender wise.
Ans) SELECT GENDER,COUNT(NAME) FROM EMPLOYEE GROUP BY GENDER;
19.2 Show department name and number of employee department in that department.
Ans) SELECT DEPT,COUNT(NAME) FROM EMPLOYEE GROUP BY DEP;
19.3 Show how many male and female employees work in each department.
Ans) SELECT DEPT,GEN,COUNT(NAME) FROM EMPLOYEE GROUP BY DEP,GEN;
19.4 Show the average salary of each department which are having average salary greater 50000.
Ans) SELECT DEPT,AVG(SAVLARY) FROM EMPLOYEE GROUP BY DEPT HAVING AVG(SALARY)>50000;
19.5 Show the maximum and minimum salary of each department.
Ans) SELECT DEPT,MIN(SALARY),MAX(SALARY) FROM EMPLOYEE GROUP BY DEPT;
19.6 Show year and number of employee join in that year.
Ans) SELECT YEAR(DOJ), COUNT(NAME) FROM STUD GROUP BY YEAR(DOJ);
19.7 Show no. of female employee in each department.
Ans) SELECT DEPT,COUNT(NAME) FROM STUD WHERE GEN=’F’ GROUP BY DEPT;
19.8 Show no. of employee from each department who is getting salary between 50000 to 75000.
Ans) SELECT DEPT,COUNT(NAME) FROM STUD WHER SALARY BETWEEN 50000 AND 75000 GROUP BY DEPT;
19.9 Show no. of employees joined in each department in year 2015.
Ans) SELECT COUNT(NAME) FROM STUD WHER YEAR(DOJ)=2015 GROUP BY DEPT;
19.10 Show average salary of each department in decreasing order of average salary.
Ans) SELECT DEPT,AVG(SALARY) FROM STUD GROUP BY STUD ORDER BY AVG(SALARY) DESC;
19.11 Show department name and number of employee department in each department having number of
employee less than 20.
Ans) SELECT DEPT,COUNT(NAME) FROM EMPLOYEE GROUP BY DEP HAVING COUNT(NAME)<20;
#AGGREGRATION FUNCTION
20.1 Find the maximum and minimum salary and also show difference between maximum salary and
minimum salary.
Ans) SELECT MAX(SALARY),MIN(SALARY),MAX(FEES)-MIN(FEES) FROM EMPLOYEE;
20.2 Find the maximum salary and minimum salary of male employee.
Ans) SELECT MAX(SALARY),MIN(SALARY) FROM EMPLOYEE WHER GEN=’M’;
20.3 Find total salary of female employees who joined in year 2015.
Ans) SELECT SUM(SALARY) FROM EMPLOYEE WHERE GEN=’F’ AND YEAR(DOJ)=2015;
20.4 How many employees joined in year 2013, 2015 and 2018?
Ans) SELECT YEAR,COUNT(NAME) FROM EMPLOYEE WHERE YEAR(DOJ) IN (2013,2015,2018);
20.5 Count how many null values in dept column.
Ans) SELECT COUNT(NAME) FROM EMPLOYEE WHERE DEPT IS NULL;
20.6 How many employees are getting salary in 5 digits?
Ans) SELECT COUNT(NAME) FROM EMPLOYEE WHER LENGTH(SALARY)=5;
20.7 Count how many employees in Sales department.
Ans) SELECT COUNT(NAME) FROM EMPLOYEE WHERE DEPT=’SALES’;
20.8 Count how many female employees in Sales department.
Ans) SELECT COUNT(NAME) FROM EMPLOYEE WHERE GEN=’F’ AND DEPT=’SALES’;
20.9 Show the sum of number of male employees in Computer Department.
Ans) SELECT COUNT(NAME) FROM EMPLOYEE WHERE DEPT=’COMPUTER’ AND GEN=’M’ ;
20.10 Count how many employees have letter ‘A’ in their name.
Ans) SELECT COUNT(NAME) FROM EMPLOYEE WHERE NAME LIKE ‘%A%’;

You might also like