IP_PRACTICAL EXAM _Revision
IP_PRACTICAL EXAM _Revision
1)Write a menu driven program using python to create CSV file in the given Structure and perform the following
operations in the menu item as per user choice.[5]
Airways
a.Display the details of students who have scored at least 90% in the final Marks percentage.
b.Rename the columns Midterm, project and final as SA1, SA2 and Annual_exam.
c.Delete the student info whose annual_exam score is less than 90.
d.Add a new column named total_marks and calculate (Sa1+sa2+Annual_exam) for each student.
e.Update Sa2 marks of a student whose id is 6889.
f. Display the column indes, row index of the above adatframe.
b) Write a Python program to display a BAR CHART of the number of students in a school.
Sample data: Group: I,II,III,IV and Strength: 38,30,45,49
1. Use different colors for each bar.
2. Title for x axis should be ‘Groups’ and title for y axis should be ‘Number of Students’
3. Ensure the title of chart is “Group wise Students” and grid line must be shown.
Answer:-
1)
#Practical bY Iman SuLTAN 12 h
import pandas as pd
import numpy as np
#1
df_data={'StudentID': [4560,5540,6889,6817],
'Homework':[100,85,92,65],
'Midterm':[97,90,85,85],
'Project':[100,88,88,87],
'Final': [95,90,87,89]}
df=pd.DataFrame(df_data)
df.to_csv("Airways.csv", index=False)
airways=pd.read_csv("Airways.csv")
print("\n\nQuestion 1 \nA\n\n\n")
print ("DataFrame airways\n", airways)##
ch='ch'
while ch!='0':
ch=str(input("\n a \n b \n c \n d \n e \n f \n 0:Exit \nEnter Question: "))
if ch=='a':
print("\nDisplay details of students who have scored at least 90% in final marks percentage\n")
print(airways[airways['Final']>=90])
elif ch=='b':
print("\nRename columns midterm, project, and final as sa2, sa1, sa2, and annual_exam\n")
airways.rename(columns={'Midterm': 'SA1',
'Project':'SA2',
'Final': 'Annual_Exam'}, inplace=True)
print(airways)
elif ch=='c':
print("\nDelete student info whose annual_exam is less than 90\n")
ind_list=[]
for j in airways.index:
if airways.loc[j, 'Annual_Exam']<90:
ind_list.append(j)
airways_drop=airways.drop(index=[j for j in ind_list], axis=0) ##
print(airways_drop) ##
elif ch=='d':
print("Add new column names total_marks and calculate (sa1+sa2+annual_exam) for each student\n")
airways['Total_Marks']=airways['SA1']+airways['SA2']+airways['Annual_Exam']
print(airways)
elif ch=='e':
print("\nUpdate sa2 marks of student whose id is 6889\n")
col_name=str(input("Enter Column Name: ")) ##
ID=int(input("Enter StudentID: ")) ##
for j in airways.index:
if airways.loc[j, 'StudentID']==ID: ##
IND=j
break
print(f"At {col_name} and {j}, {ID}, value is: {airways.loc[j,col_name]} \n") ##
upd_id=int(input("Enter new value: "))
airways.loc[IND, col_name]=upd_id ##
print(airways)
elif ch=='f':
print("Display column index, row index of above data frame")
print("Column Index: ", airways.columns.values)
print("Row Index: ", airways.index)
elif ch=='0':
print("\nThank you! \nEnd of Question 1 a")
ch='0'
break
else:
print("\nTry again")
print("B")
import matplotlib.pyplot as plt
import numpy as np
plt.grid(True)
plt.show()
2)
create database prac_sql_I_H;
use prac_sql_I_H;
Answer:-
import pandas as pd
import matplotlib.pyplot as plt
while True:
cric23=pd.DataFrame({'SNO':[1,2,3,4,5],'Batsman':['Virat Kohli','Rohit Sharma','Quinton De
Kock','Rachin Ravindra','Daryl Mitchell'],'Innings':[11,11,10,10,8],'Runs':[765,597,594,578,418],'SR':
[90.32,125.95,107.03,106.45,111.07]} )
print('''
1.Display batsman name and runs
2.Add column
3.Change data
4.Delete data
5.Bar graph
6.export to csv''')
print(cric23)
y=int(input("enter choice:"))
if y==1:
x=int(input("enter number of records needed:"))
L=[]
for i in range(x):
sno=int(input("enter sno number of player:"))
L.append(sno-1)
print(cric23.loc[L,['Batsman','Runs']])
if y==2:
name=input("enter column name:")
col1=input("enter first column operand:")
col2=input("enter second column operand:")
pos=int(input("enter column index:"))
cric23[name]=cric23[col1]/cric23[col2]
print(cric23)
if y==3:
index=1
name=input("enter name of batsman whose record to be edited:")
for i in range(len(cric23)):
if cric23.loc[i,'Batsman']==name:
index==i
cols=int(input("enter number of columns to be edited:"))
for i in range(cols):
col=input("enter column name:")
val=eval(input("enter new value:"))
cric23.loc[i,col]=val
print(cric23)
if y==4:
col=input('enter colun on basis of which record to be deleted:')
x=eval(input("enter value for which if lesser record is deleted:"))
L=[]
for i in range(len(cric23)):
if cric23.loc[i,col]<x:
L.append(i)
cric23.drop(L,axis=0,inplace=True)
print(cric23)
if y==5:
x=input('enter column to be graphed:')
xvalues=list(cric23['Batsman'])
yvalues=list(cric23[x])
plt.bar(xvalues,yvalues)
plt.xlabel('Batsman')
plt.ylabel(x)
plt.title('Batsman vs'+x)
plt.show()
if y==6:
cric23.to_csv('TOP5.csv')
print('done
2)
create database db1;
use db1
create table Shop4(
Id varchar(30) primary key,
SName varchar(50),
Area varchar(50),
Bonus decimal(10,3),
DateofOpen date);
insert into Shop4 (Id,SName,Area,Bonus,DateofOpen) values
('S001','ABC Computronics','CP',1000.89,'2010-11-20'),
('S002','All Infotech','GK II',2345.987,'2015-09-12'),
('S003','Tech Shoppe','CP',761.46,'2013-07-25'),
('S005','Geek Tenco Soft','Nehru Place',456.923,'2019-10-10'),
('S006','Hitech Solution','GK II',1000.025,'2008-12-20');
select * from Shop4
select Sname,round(Bonus) from Shop4
select Sname, instr(Sname,'tech') from Shop4
select mid(Sname,2,3) from Shop4
select SName,monthname(DateofOpen) from Shop4
select Area,sum(Bonus), avg(Bonus), min(Bonus),max(bonus) from Shop4
group by Area
select Area,count(Sname) from Shop4
group by Area
select * from Shop4
order by DateOfOpen desc
Answer:-
1)
import pandas as pd
import matplotlib.pyplot as plt
while True:
print("""
Press 1 to add a new column.
Press 2 to display select countries' population and birthrate.
Press 3 to list all records with birthrate above specified number.
Press 4 to remove records where birthrate is above specified number.
Press 5 to add a new record.
Press 6 to modify a cell's value.
Press 7 to plot a bar graph.
Press 8 to exit program.
""")
(a,b)=df.shape
ch=int(input("Enter your choice here: "))
if ch==1:
l1=[]
name=input("Enter Column name here:")
for i in range(len(df)):
x=input("Enter your value here: ")
l1.append(x)
df[name]=l1
print(df)
if ch==2:
x=int(input("Enter first row index to view: "))
y=int(input("Enter last row index to view: "))
print(df.iloc[x:y,0:3])
elif ch==3:
l=[]
x=int(input("Enter value for birthrate to be greater than: "))
for i in range(len(df)):
if df.iat[i,2]>x:
l.append(i)
print(df.iloc[l,:])
elif ch==4:
l=[]
x=int(input("Enter value for birthrate to be greater than: "))
for i in range(len(df)):
if df.iat[i,2]>x:
l.append(i)
df.drop(l, axis=0,inplace=True)
print(df)
elif ch==5:
l=[]
for i in range(b):
x=eval(input("Enter your values here: "))
l.append(x)
df.loc[a]=l
print(df)
elif ch==6:
x=int(input("Enter row index: "))
y=int(input("Enter column index: "))
val=eval(input("Enter new value: "))
df.iat[x,y]=val
print(df)
elif ch==7:
x=df["Country"]
y=df["Population "]
plt.bar(x,y, color=['blue','red','orange','pink','black', 'brown', 'yellow'])
plt.title("Countries and their populations")
plt.xlabel("Countries")
plt.ylabel("Population")
plt.grid()
plt.show()
elif ch==8:
print("Thank you for using this menu driven program!")
break
2)
create database anya_practical;
use anya_practical;
create table staff (Sid int primary key not null,
sname varchar(20) not null,
designation varchar(20) not null,
salary int not null,
dojoin date not null,
section varchar(20) not null);
insert into staff values (1001, "Sagar", "PGT", 87000, '2010-11-02', "Residential Section"),
(1002, "Ankit", "Clerk", 24000, '2010-04-01', "Office"),
(1003, "Dhwani", "Clerk", 22000, '2009-01-05', "Office"),
(1004, "Jenil", "PRT", 34000, '2009-07-25', "Primary"),
(1005, "Roshni", "PGT", 73000, '2008-07-17', "Senior"),
(1006, "Mital", "TGT", 41000, '2008-04-08', "Middle"),
(1007, "Gagan", "Lab Assistant", 24000, '2009-11-23', "Office");
select * from staff;
1)
i.Write a menu driven program using python to create Dataframe in the given structure and perform the following
operations in the menu item as per user choice.
Bookdetails:
Answer:-
import pandas as p
import numpy as np
import matplotlib.pyplot as m
1)
i.
df = p.DataFrame([[1,"Data Structure","Lipschute","DS","McGraw",4,217.00],[2,"DOS
Guide","NORTRON","OS","PHI",3,175.00],
[3,"Turbo C++","Robort Lafore","Frog","Galgotia",5,270.00],[4,"Dbase
Dummies","Palmer","DBMS","PustakM",7,130.00],
[5,"Mastering Windows","Cowart","OS","BPB",1,225.00],[6,"Computer
Studies","French","FND","Galgotia",2,75.00]],
columns=["No.","Title","Author","Subject","Publisher","Quantity","Price"])
while True:
print('''Please choose from the follwing options:
1. Display the Dataframe
2. Add new column “Total”.(Note: total=Quantity*price)
3. Display the records whose total is greater than 500.
4. Change the column name “Quantity”to “QTY”.
5. Delete the 2nd and 4th Row.
6. Display column names and total no.of rows of the Given Dataframe.
7. Exit''')
ch = int(input("Please enter your choice:"))
print()
if ch == 1:
print(df)
print()
elif ch == 2:
df["Total"] = df.Quantity * df.Price
print(df)
print()
elif ch == 3:
print(df[df.Total>500])
print()
elif ch == 4:
df.rename(columns={"Quantity":"QTY"},inplace=True)
print(df)
print()
elif ch == 5:
df.drop(df.iloc[[1,3]].index,inplace=True)
print(df)
print()
elif ch == 6:
print("The column names are:")
for i in df.columns:
print(i)
print("Total number of rows are",len(df.index))
elif ch == 7:
break
else:
print("Please enter valid choice")
print()
#ii)
m.bar(["MUMBAI","DELHI","RAJASTHAN","KOLKATA","GOA"],[88,78,102,43,85m.xlabel("Teams")
m.ylabel("Runs")
m.title("ODI Scores")
m.show()
2)
a.select class, count(*) from student group by class having count(*)>2
b.select class,avg(Marks) from student where class=’XI’ or class=’XII’ group by class
c.select name, max(DOB) from student
d.select upper(name),Rollno from student where marks>250;
e.select name,instr(name,’e’) from student where marks between 300 and 450;
f. select month(DOB) from student where class=”XII”;
g. Select length(name) from student where name like ‘%L” or name like “%Y”;
Laptop:
strength 40 50 43 35 38 49
b. To display a report listing ItemName, Type and Price in descending order of Price.
c. Display the month name for the date of stock of type ‘office Table’
f. To display the sum and average price of items in each type where item either “RedRose” or “Park sitting”.
Answer:-
import pandas as p
import numpy as np
import matplotlib.pyplot as m
while True:
print(''Please choose from the follwing options:
1. Create a Dataframe from the CSV and display.
2. Add a newcolumn totaamount and calculate(price*quantity)l for each product.
3. Display the records whose price is either 40000 or 53000
4. Display all the information of laptop A112 and A115.
5. Update apple laptop price to 100000
6. Rename the rowindex A111 to A115 as L01 to L05
7. Delete L05 information from the dataframe.
8. Exit'')
ch = int(input("Please enter your choice:"))
print()
if ch == 1:
df = p.read_csv('Q3.csv',header=0)
df.set_index("L_NO",inplace=True)
print(df)
print()
elif ch == 2:
df["TotalAmount"] = df["Price"]*df["Qty"]
print(df)
print()
elif ch == 3:
print(df[(df.Price==40000)|(df.Price==53000)])
print()
elif ch == 4:
print(df[(df.L_NO=='A112')|(df.L_NO=='A115')])
print()
elif ch == 5:
df.at[df[df.Company=='Apple'].index[0],"Price"] = 100000
print(df)
print
elif ch == 6:
df.rename(index =
{"A111":"L01","A112":"L02","A113":"L03","A114":"L04","A115":"L05"},inplace=True)
print(df)
print()
elif ch == 7:
df.drop("L05",inplace=True)
print(df)
print()
elif ch == 8:
break
else:
print("Please enter valid choice")
print()
#b)
import matplot.pyplot as m
import pandas as p
df =
p.DataFrame([40,50,43,35,38,49]},index=p.Series(["12A","12B","12C","12D","12E","12F"],name="Class"))
df.plot(kind="bar",width=0.5,edgecolor="green",color="yellow")
m.title("Grade XII Class Wise Strength")
m.xlabel(“Class”)
m.ylabel(“Strength”)
m.show()
2)
a.SELECT itemname ,COUNT(type) FROM INTERIORS group by Type.;
e. select pow(5,mod(15,4));
f. Select airlines, sum(price), avg(price) from interior groupby type where itemname =”REDROSE” or
itemname=”PARKSITTING”;
g. SELECT itemname from Interior WHERE itemname like ‘%soft’;
DELHI PRIVATE SCHOOL – DUBAI
Day 1 2 3 4 5 6 7
Table – Charity
Answer:
import pandas as p
import numpy as np
import matplotlib.pyplot as m
#i
print("Q1a")
df=p.read_csv('Items.csv')
print(df)
ans='yes'
while ans=="y" or ans=='yes':
print('Choose any of the following options:')
print('1. Show DataFrame')
print('2. Append new row to the DataFrame')
print('3. Display Item, Price columns of Dataframe')
print('4. Update the price of chair to 3000.')
print('5. Delete an item whose price is less than 2500')
print('6. Rename the column “color” as “furniture color”')
print('7. Exit')
choice=(int(input("Enter an option by giving its serial number:")))
if choice==1:
df=p.read_csv('items.csv')
print(df)
if choice==2:
df=df.append({'Item':'Cupboard','Material':'Hardwood','Colour':'Black','Price':3000},ignore_index=True)
print(df)
if choice==3:
print(df.loc[:,['item','price']])
if choice==4:
if choice==5:
print(df.drop(df[df['price']<2500].index))
if choice==6:
df.rename(columns={'Colour':'Furniture color'},inplace=True)
print(df)
if choice==7:
print()
print("Thank you")
break
#ii
print("Q1b")
Day=[1,2,3,4,5,6,7]
TicketsSold=[2000,2800,3000,3500,1000,1500,2100]
m.title("Tickets sold analysis")
m.plot(Day,TicketsSold,linestyle='-',color="magenta",label="Tickets Sold")
m.legend(["Tickets Sold"],loc="best")
m.show()
2.
a) Display the name of week day when socks purchased.
2)
a.SELECT candidateid, candidatename, POW(marks, 2) AS square_of_marks FROM Candidate;
b.SELECT candidateid, candidatename, examdate, round(marks) AS marks_without_decimal
FROM Candidate
WHERE batch IN ('Batch1', 'Batch2');
c.SELECT MAX(marks) AS max_marks, MIN(marks) AS min_marks, SUM(marks) AS total_marks FROM
Candidate;
d.SELECT COUNT(*) AS commerce_students_count FROM Candidate WHERE stream = 'Commerce';
e.SELECT UPPER(candidatename) AS name_in_capitals FROM Candidate;
f.SELECT LEFT(candidatename, 2) AS first_two_letters FROM Candidate;
g.SELECT batch, AVG(marks) AS average_marks FROM Candidate GROUP BY batch;
h.SELECT candidatename, batch, marks, stream, DAYNAME(examdate) AS day_of_week FROM Candidate;