0% found this document useful (0 votes)
36 views31 pages

Kis W Class 12 Practical File

Uploaded by

abdullahmaruf312
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)
36 views31 pages

Kis W Class 12 Practical File

Uploaded by

abdullahmaruf312
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/ 31

PROGRAM-1

Create a pandas series from an ndarray

#import the pandas lib as pd


import pandas as pd
# create an array
import numpy as np
S=pd.Series(np.array([11,12,13,14,15,16,17,18,19]))
print(S)

OUTPUT:-

1
PROGRAM-2

Create a pandas series from a dictionary of values.

#import the pandas lib as pd


import pandas as pd
#create a dictionary
dictionary={"A":10,"B":20,"C":30}
#create a series
Series=pd.Series(dictionary)
print(Series)

OUTPUT:-

2
PROGRAM-3

Write a program to access Data from Series with indexing and slicing

import pandas as pd
s = pd.Series([11,22,63,74,95],index = ['a','b','c','d','e'])
print(s)
print(s[0])# for 0 index position
print(s[:3]) #for first 3 index values
print(s[-3:]) # slicing for last 3 index values

OUTPUT:-

3
PROGRAM-4
Find the sum of each column, or find the column with the lowest
mean
import pandas as pd
Profit={'TCS':{'Qtr1':2500,'Qtr2':2000,'Qtr3':3000,'Qtr4':2000},
'WIPRO':{'Qtr1':2800,'Qtr2':2400,'Qtr3':3600,'Qtr4':2400},
'L&T':{'Qtr1':2100,'Qtr2':5700,'Qtr3':35000,'Qtr4':2100}}
df=pd.DataFrame(Profit)
print(df)
print()
print('Column wise sum in dataframe::')
print(df.sum(axis=0))
print()
print('Column wise mean value::')
print(df.mean(axis=0))
print()
print('Column with minimum mean value::')
print(df.mean(axis=0).idxmin())
OUTPUT:-

4
PROGRAM-5

Create a Data Frame df1 from a list with the columns Name and Age.

import pandas as pd1


data = [['Meena',15],['Mohan',18],['Deep',19]]
df1 =pd1.DataFrame(data,columns=['Name','Age'])
print(df1)

OUTPUT:-

5
PROGRAM-6

Replace all negative values in a Data Frame with 0.

import pandas as pd
dic={'Data1':[-2,-3,5,6,7,-4],'Data2':[4,1,5,6,-2,-1]}
df=pd.DataFrame(dic)
print(df)
print("DataFrame after replacing negative values with 0:")
df[df<0]=0
print(df)

OUTPUT:-

6
PROGRAM-7

Replace all the missing values in a DataFrame with 999.

import pandas as pd
import numpy as np
empdata={'empid':[101,102,103,104,105,106],
'empname':['Meena','Arun','Deena',np.nan,'Beena','Daron'],
'DOJ':['13-02-2003','24-05-2005','02-09-2002','12-06-2001',
np.nan,'22-04-2002']}
df=pd.DataFrame(empdata)
print(df)
df=df.fillna({'empname':999,'DOJ':999})
print()
print(df)
OUTPUT:-

7
PROGRAM-8

Create a Data Frame quarterly sales 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
dic={'itemcat':['Car','AC','Aircooler','Washing Machine'],
'itemname':['Ford','Hitachi','Symphony','LG'],
'expenditure':[7000000,50000,12000,14000]}
quartsales=pd.DataFrame(dic)
print(quartsales)
qs=quartsales.groupby('itemcat')
print('Result after filtering DataFrame')
print(qs['itemcat','expenditure'].sum())

OUTPUT:-

8
PROGRAM-9

Create a data frame for examination result and display row labels,
column labels data types of each column,shapes and the dimensions
import pandas as pd
dic={'class':['I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'],
'PassPercentage':[100,100,100,100,100,100,100,100,100,98.6,100,99]}
result=pd.DataFrame(dic)
print(result)
print(result.dtypes)
print('shape of DataFrame is:::::')
print(result.shape)
print('Dimensions of DataFrame is:::::')
print(result.ndim)
OUTPUT:-

9
PROGRAM-10

Filter out rows based on different criteria such as duplicate rows.

import pandas as pd
dic={'Name':['Rohit','Mohit','Deepak','Rohit','Deepak','Sohit','Geeta'],
'MarksinIP':[85,45,92,85,92,96,84]}
marks=pd.DataFrame(dic)
duplicateRow = marks[marks.duplicated(keep=False)]
print(duplicateRow)
OUTPUT:-

10
PROGRAM-11

Write a program to plot a line chart with the given data


x=[5,8,2] and y=[2,6,8]

import matplotlib.pyplot as plt


x=[5,8,2]
y=[2,6,8]
plt.plot(x,y)
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
OUTPUT:-

11
PROGRAM-12

Below is given the velocity of a moving body at different instances of


time. Draw the velocity time graph.
Time(s) 0 5 10 15 20 25 30
Velocity(m/s) 10 15 20 20 30 15 0

import matplotlib.pyplot as plt


t=[0,5,10,15,20,25,30]
velocity=[10,15,20,20,30,15,0]
plt.plot(t,velocity)
plt.xlabel('Velocity m/s')
plt.ylabel('Time(s)')
plt.title('Velocity-Time')
plt.show()
OUTPUT:-

12
PROGRAM-13
Given the school result data,analyse the performance of the students
on different parameters,eg:subject wise
import matplotlib.pyplot as plt
Subject=['Physics','Chemistry','Hindi','Biology','ComputerSc']
Percentage=[85,78,65,90,100]
plt.bar(Subject,Percentage,align='center',color='green')
plt.xlabel('SUBJECTS NAME')
plt.ylabel('PASS PERCENTAGE')
plt.title('Bar Graph For Result Analysis')
plt.show()
OUTPUT:-

13
PROGRAM-14
Importing and exporting data between pandas and CSV file.
import pandas as pd
df=pd.read_csv("C:\\Users\\Lenovo\\Desktop\\emp.csv")
print(df)
OUTPUT:-

import pandas as pd
l=[{'Name':'Sachin','SirName':'Bhardwa'},{'Name':'Vinod','SirName':'Ve
rma'},{'Name':'Rajesh','SirName':'Mishra'}]
df1=pd.DataFrame(l)
df1.to_csv("C:\\Users\\Lenovo\\Desktop\\Dataframel.csv")
OUTPUT:-

14
PROGRAM-15
For the Data Frames create above, analyze, and plot appropriate
charts with title and legend.
import matplotlib.pyplot as plt
import numpy as np
s=['1st','2nd','3rd']
per_sc=[95,89,77]
per_com=[90,93,75]
per_hum=[97,92,77]
x=np.arange(len(s))
plt.bar(x,per_sc,label="science",width=0.5,color="green")
plt.bar(x+.25,per_com,label="commerce",width=0.25,color="red")
plt.bar(x+.50,per_hum,label="humanities",width=0.25,color="gold")
plt.xticks(x,s)
plt.xlabel("position")
plt.ylabel("percentage")
plt.title("Bar Graph For Result Analysis")
plt.legend()
plt.show()
OUTPUT:-

15
MY SQL - I
TABLE: - TEACHER
NO NAME AGE DEPT DOJ SALARY SEX

1 JUGAL 34 COMPUTER 1994-01-10 10000 M

2 SHARMILA 31 HISTORY 1998-03-24 12000 F

3 SANDEEP 32 MATHS 1996-12-12 20000 M

4 SANGEETHA 35 HISTORY 1999-07-01 15000 F

5 RAKESH 42 COMPUTER 1998-06-27 16000 M

i) Create the table Teacher with the following attributes and records.
Create table Teacher (NO Int(5),
NAME Varchar (25),
AGE Int (2),
DEPT Char (20),
DOJ Date,
SALARY Int (12),
SEX Char (1));
To insert above records:
Insert into teacher values (1,'JUGAL',34,'COMPUTER','1994-01-10',10000,'M');
Insert into teacher values (2,'SHARMILA',31,'HISTORY','1998-03-24',12000,'F');
Insert into teacher values (3,'SANDEEP',32,'MATHS','1996-12-12',20000,'M');

16
Insert into teacher values (4,'SANGEETHA',35,'HISTORY','1999-07-01',15000,'F');
Insert into teacher values (5,'RAKESH',42,'COMPUTER','1998-06-27',16000,'M');
ii) To display all the information about the teachers of History department whose
name starts with the letter S.
Select * from teacher where dept='History' and name like 'S%';
iii) To display the names of female teachers who are in Math department.
Select name from teacher where sex='F' and dept='Maths';
iv) To display the names and departments of all teachers with their date of joining in
descending order.
Select name, dept, doj from teacher order by doj desc;
v) To increase the salary by 500 for all the teacher working in computer department.
Update teacher set salary=salary+500 where dept='Computer';
vi) To insert a new row in the teacher table with the following data:
[7, ’Raj’, 26, ‘computer’, ‘1995-05-13’, 20000, ‘M’]
Insert into teacher values (7,'Raj',26,'Computer','1995-05-13', 20000,'M');
vii) To count the number of teachers with age>23.
Select count (*) from teacher where age>23;
viii) To display the different department in the teacher table.
Select distinct (Dept) from teacher;
ix) To remove all the teachers who joined after 1998.
Delete from teacher where doj>'1997-12-31';
x) To add a new column called Address in the above table.
Alter table teacher add Address varchar (35);
xi) Write a command to view the structure of the above table
Desc teacher;

17
xii) To change dept column to DEPARTMENT in the above table
Alter table teacher change DEPT DEPARTMENT Char (20);

Write out puts for the following with respect to the original Table:
a) Select Count(Distinct Dept ) From Teacher;

b) Select Max(Age) from Teacher where Sex=’F’;

18
c) Select Avg(Salary) from teacher where Sex=’M’;

d) Select Name, Age from Teacher Order By salary Desc;

19
MY SQL - II
TABLE: - HOSPITAL
PNO Name Age Department DOA Charges Sex

1 Arpit 62 Surgery 1999-09-12 300.50 M

2 Zarina 22 ENT 2000-07-13 250.75 F

3 Karina 32 Orthopedic 1998-05-04 275.25 F

4 Arun 12 Surgery 1999-12-31 300.25 M

5 Zubin 30 ENT 2005-08-01 250.75 M

6 Ketaki 16 ENT 2009-09-01 350.50 F

7 Ankita 29 Cardiology 2010-12-10 400.50 F

a) Create Table Hospital with the following attributes and records


CREATE TABLE HOSPITAL(PNO INT(2),
NAME VARCHAR(20),
AGE INT(2),
DEPARTMENT VARCHAR(25),
DOA DATE,
CHARGES FLOAT(5,2),
SEX CHAR(1));
INSERT INTO HOSPITAL VALUES(1,"ARPIT",62,"SURGERY","1999-09-12",300.50,'M');
INSERT INTO HOSPITAL VALUES(2,"ZARINA",22,"ENT","2000-07-13",250.75,'F');
20
INSERT INTO HOSPITAL VALUES(3,"KARINA",32,"ORTHOPEDIC","1998-05-
04",275.25,'F');
INSERT INTO HOSPITAL VALUES(4,"ARUN",12,"SURGERY","1999-12-31",300.25,'M');
INSERT INTO HOSPITAL VALUES(5,"ZUBIN",30,"ENT","2005-08-01",250.75,'M');
INSERT INTO HOSPITAL VALUES(6,"KETAKI",16,"ENT","2009-09-01",350.50,'F');
INSERT INTO HOSPITAL VALUES(7,"ANKITA",29,"CARDIOLOGY","2010-12-10",
400.50,'F');
b) To display the names of the patients in uppercase and departments in lowercase
for female patients in ENT.
SELECT UCASE(NAME),LCASE(DEPARTMENT) FROM HOSPITAL WHERE SEX='F'AND
DEPARTMENT LIKE 'ENT';
c) To return the second to fourth character from departments for all male patients.
SELECT SUBSTR(DEPARTMENT,2,3) FROM HOSPITAL WHERE SEX='M';
d) To list the position of character ‘a’ in the names of patients who are aged over 50.
SELECT INSTR(NAME,'A') FROM HOSPITAL WHERE AGE >50;
e) To display first four characters of department field who were admitted before
2008.
SELECT SUBSTR(DEPARTMENT,1,4) FROM HOSPITAL WHERE YEAR(DOA)<2008;
f) To display number and length of department and name of the patient in surgery
department.
SELECT PNO,LENGTH(DEPARTMENT),NAME FROM HOSPITAL WHERE DEPARTMENT
LIKE "SURGERY";
g) To display month and year of admission of Zarina.
SELECT MONTH(DOA),YEAR(DOA) FROM HOSPITAL WHERE NAME LIKE 'ZARINA';
OR
SELECT MONTHNAME(DOA),YEAR(DOA) FROM HOSPITAL WHERE NAME LIKE
'ZARINA';

21
h) Round of Charges to 1 decimal place for all patients admitted in 1998 and who
are aged above 50.
SELECT ROUND(CHARGES,1) FROM HOSPITAL WHERE YEAR(DOA) =1998 AND AGE
>50;
i) Round of charges to nearest tens for all those in Cardiology department in
descending order of charges.
SELECT ROUND(CHARGES,-1) FROM HOSPITAL WHERE DEPARTMENT LIKE
"CARDIOLOGY" ORDER BY CHARGES DESC;
j) To display the first 4 characters of names in capitals and last 4 characters of
department in small letters whose date of appointment is in JULY.
SELECT UCASE(SUBSTR(NAME,1,4)),LCASE(SUBSTR(DEPARTMENT,-4))FROM
HOSPITAL WHERE MONTHNAME(DOA)='JULY';
k) To display the name of Month, Day of Month for all those Female patients in
Surgery department
SELECT MONTHNAME(DOA),DAY (DOA) FROM HOSPITAL WHERE SEX='F'
AND DEPARTMENT LIKE 'SURGERY';
l) To display all the names and departments of patients whose name starts with A in
descending order of their charges.
SELECT NAME,DEPARTMENT FROM HOSPITAL WHERE NAME LIKE 'A%'
ORDER BY CHARGES DESC;

22
m) Write the output for the following queries:-
(i) Select MOD(27,4), SIGN(POW(-3,3));

(ii) Select ROUND(26.789,2),ROUND(45.34),ROUND(285.678,-2);

23
(iii) Select MONTHNAME(DOA),DAY(DOA) from hospital where department<>’ENT’
or name like ‘%a’;

(iv) Select SUBSTR(Name,2,4),INSTR(Department,’N’) from Hospital where Sex=’F’;

24
MY SQL - III
TABLE: - SPORTS

STUDENTID NAME GENDER DATEADMIT GAME FEES

S101 Ann F 2015-09-12 Cricket 34000

S102 Simran F 2014-08-15 Lawn Tennis 50000

S103 Divya F 2017-11-01 Badminton 55000

S104 Fauzia F 2016-12-09 Lawn Tennis 60000

S105 Tom M 2017-12-10 Badminton 50000

S106 Shashank M 2016-09-14 Cricket 45000

S107 Trpiti F 2015-02-10 Badminton 40000

a) Create Table Sports with the following attributes and records.


Create Table Sports
(StudentidChar(4),
Name Varchar(20),
Gender Char(1),
DateAdmit Date,
Game Varchar(15),
Fees int(5));

25
Insert Into Sports Values(‘S101’,’Ann’,’F’,’2015-09-12’,’Cricket’,34000);
Insert Into Sports Values(‘102’,’Simran’,’F’,’2014-08-15’,’Lawn Tennis’,50000);
Insert Into Sports Values(‘S103’,’Divya’,’F’,’2017-11-01’,’Badminton’,55000);
Insert Into Sports Values(‘S104’,’Fauzia’,’F’,’2016-12-09’,’Lawn Tennis’,60000);
Insert Into Sports Values(‘S105’,’Tom’,’M’,’2017-12-10’,’Badminton’,50000);
Insert Into Sports Values(‘S106’,’Shashank’,’M’,’2016-09-04’,’Cricket’,45000);
Insert Into Sports Values(‘S107’,’Tripti’,’F’,’2015-02 10’,’Badminton’,40000);
b) To view all the records inserted in the above table.
Select * from Sports;
c) To display the maximum and minimum fees for each type of game.
Select Game,Max(Fee),Min(Fee) From Sports Group By Game;
d) To display the different games in the above table.
Select Distinct Game from Sports;
e) To display the sum of fees of male students learning Cricket.
Select Sum(Fees) from Sports where Game=’Cricket and Gender=’M’;
f) To display the number of female students learning Badminton.
Select Count(*) From Sports Where Game=’Badminton’ and Gender=’F’;
g) To display average fees of each gender type.
Select Gender, Avg(Fees) From Sports Group By Gender;
h) To display games and sum of fees of each game whose sum is greater than
100000.
Select Game, Sum(Fees) From Sports Group By Game Having Sum(Fees)>100000;
i) To count the number of female students in either LAWNTENNIS or BADMINTON
Select Count(*) from Sports where Gender=’F’ and Game in(‘Lawn
Tennis’,’Badminton’);

26
j) To display the maximum, minimum and Average Fees Game wise where the
number of students is greater than 2.
Select Game,Max(Fees),Min(Fees),Avg(Fees) from Sports Group By Game having
Count(*)>2;
k) To display the difference between maximum and minimum fees gender wise.
Select Gender, Max(Fees)-Min(Fees) as “DIFFERENCE’ From Sports Group By
Gender;
l) To display the total fees of students admitted in the year 2015
Select Sum(Fees) From Sports Where Year(Dateadmit)=2015;

k. Give the output for the following queries based on table SPORTS:

(i) Select COUNT(DISTINCT GAME) from sports;

27
(ii) Select GAME,SUM(FEES) from sports group by game;

(iii) Select GENDER,MAX(FEES),MIN(FEES),COUNT(STUDENTID) from sports group by


gender;

(iv) Select Game, Max(Fees),Avg(Fees)) from Sports group by Game having


count(*)>2;

28
MY SQL - IV
Consider the tables given below and answer the questions that follow:
Table: Event
EventId Event NumPerformers CelebrityID
101 Birthday 10 C102
102 Promotion Party 20 C103
103 Wedding 12 C102
104 Wedding 15 C104

Table: Celebrity
CelebrityId Name Phone FeeCharged
C101 Faiz Khan 99101956 200000
C102 Sanjay Kumar 89346644 250000
C103 Neera Khan Kapoor 98116656 300000
C104 Reena Bhatia 65877756 100000
Write the SQL queries for the following:
a) To create a join of above two table eliminating the identical column.
Ans: Select * from Event natural join Celebrity;

b) To display EventId, Event and Celebrity for only those events that have more
than 10 performers.
Ans: Select EventId, Event, name from Event, Celebrity where
Event.CelebrityId=Celebrity.CelebrityId and numperformers>10;

c) To create a Cartesian product of event and celebrity.


Ans: Select * from Event, Celebrity;

d) To display Name,Phone,Feecharged from Celebrity;


Ans: Select name,phone ,Feecharged from Celebrity;

Write the output for the following:


e) Select name,phone from Event, Celebrity where Event. CelebrityId=Celebrity.CelebrityId;
Ans:
Name Phone
Sanjay Kumar 89346644
Sanjay Kumar 89346644
Neera Khan Kapoor 98116656
Reena Bhatia 65877756
f) Select count(distinct event) from Event;
Ans:
count(distinct event)
3

29
MY SQL - V

In a database company, there are two tables given below:


Table: Sales
SalesmanId Name Sales LocationId
S1 Anita Singh Arora 250000 102
S2 T.P.Singh 1300000 101
S3 Tina Jaiswal 1400000 103
S4 Gurdeep Singh 1250000 102
S5 Simi Faizal 1450000 103

Location
LocationId LocationName
101 Delhi
102 Mumbai
103 Kolkata
104 Chennai
Write the SQL queries for the following:
a) To display all rows of Sales table even if it doesn’t have a matching value in
Location table.
Ans: Select * from Sales left join location on
(Sales.LocationId=Location.LocationId);
b) To display SalesmanId,Name whose name beginning with letter T.
Ans: Select SalesmanId, Name from sales where name like ‘T%’;
c) To create a Cartesian product of sales and location.
Ans: Select * from sales, location;
(For Viva question here Cartesian product = 9 rows and columns=6)
d) To display names of salesman,sales and corresponding location names who have
achieved sales more than 1400000.
Ans: Select name,sales,locationname from sales,location where
sales.locationid=location.locationid and Sales >140000;
Write the output for the following:
e) Select salesmanid,name,sales.locationid,locationname from sales,location where
sales.locationid=location.locationid;
Ans:
SalesmanId Name LocationId LocationName
S2 T.P.Singh 101 Delhi
S1 Anita Singh Arora 102 Mumbai
S4 Gurdeep Singh 102 Mumbai
S3 Tina Jaiswal 103 Kolkata
S5 Simi Faizal 103 Kolkata

30
f) Select max(Sales), min(Sales) from sales;
Ans:
Max(sales) Min(sales)
1450000 250000

31

You might also like