XII-IP-Record (2024.25)
XII-IP-Record (2024.25)
25)
PYTHON RECORD PROGRAMS : 1 to 20
1. Create a panda’s series from a dictionary of values and a ndarray
Program:
#importing pandas library
import pandas as pd
#importing numpy library
import numpy as np
#Creating series from a dictionary
d={'Jan':31,'Feb':28,'Mar':31,'Apr':30,'May':31}
S1=pd.Series(d)
print("Series from Dictionary")
print("----------------------")
print(S1)
#Creating series from an nd array
ar=np.array([10,20.5,30,40,50])
print("\nSeries from ndarray")
print("-------------------")
S2=pd.Series(ar)
print(S2)
Output
Series from Dictionary
----------------------
Jan 31
Feb 28
Mar 31
Apr 30
May 31
dtype: int64
Series from ndarray
-------------------
0 10.0
1 20.5
2 30.0
3 40.0
4 50.0
dtype: float64
2. Given a Series, print all the elements, whose average is >= 75.
Program:
#importing pandas library
import pandas as pd
snames=[]
smarks=[]
n=int(input("How many students averages you want to store? "))
for i in range(0,n):
name=input("Enter the name of the student " +str(i+1)+" : ")
snames.append(name)
mark=int(input("Enter the average of the student"+str(i+1)+" : "))
smarks.append(mark)
S=pd.Series(data=smarks,index=snames)
print("Details of the students whose average is more than 75 : ")
print(S[S>=75])
XII – IP 1 Record (2024.25)
Output
How many students averages you want to store? 5
Enter the name of the student 1 : Rajesh
Enter the average of the student 1 : 75
Enter the name of the student 2 : Kanna
Enter the average of the student 2 : 95
Enter the name of the student 3 : Chinna
Enter the average of the student 3 : 22
Enter the name of the student 4 : Munna
Enter the average of the student 4 : 79
Enter the name of the student 5 : Manohar
Enter the average of the student 5 : 65
Details of the students whose average is more than 75 :
Rajesh 75
Kanna 95
Munna 79
dtype: int64
3. Write a program to perform the following operations on the Series Object ‘Veg’.
Given Data:
Beetroot 40
Carrot 60
Drumstick 10
Brinjal 50
(i) Modify the Carrot value to 90.
(ii) Add the row “Tomato” with value 30.
(iii) Rename index “Brinjal” to “PennadaBrinjal”
(iv) Fetch first 3 rows using head function
(v) Fetch last 4 rows using tail function
Program:
#importing pandas library
import pandas as pd
Veg=["Beetroot","Carrot","Drumstick","Brinjal"]
Rates=[40,60,10,50]
Veg=pd.Series(data=Rates,index=Veg) #creating a series
print("Original Series Object Veg : \n")
print(Veg)
print("\nOperations on Series \n")
Veg["Carrot"]=90
print("1.Series after modifying the Carrot value..")
print(Veg)
Veg["Tomato"]=30
print("\n2.Series after adding Tomato details..")
print(Veg)
Veg.index=['Beetroot','Carrot','Drunstick','PennadaBrinjal','Tomato']
#Veg = Veg.rename(index={'Brinjal': 'PeddadaBrinjal'})
print('\n3.Series After modifying Brinjal index')
print(Veg)
print('\n4.Fetching first 3 rows using Head function')
print(Veg.head(3))
print('\n5.Fetching last 4 rows using Tail function')
print(Veg.tail(4))
Output
Original Series Object Veg :
XII – IP 2 Record (2024.25)
Beetroot 40
Carrot 60
Drumstick 10
Brinjal 50
dtype: int64
Operations on Series
Index Data
Sun 100
Mon 150
Tue 120
Wed 130
Thu 155
Fri 160
Sat 190
Week1
9. Create the following DataFrame “Trains” which contains the following train details.
TrainNo From To
HydExp 17255 Narsapur Lingampalli
NspExp 17256 Lingampalli Narsapur
Pass 77233 Bhimavaram Narsapur
Falaknuma 12704 Secunderabad Howrah
Do the following operations:
(1) Create the dataframe and display it
(2) Display the first 2 rows
(3) Display the last 2 rows
(4) Display the first 2 columns
(5) Display column “TrainNo” and “To”
Program:
#importing pandas library
import pandas as pd
#creating dictionary
dict={'TrainNo':[17255,17256,77233,12704],'From':['Narsapur','Lingampalli','Bhimavaram','Secund
erabad'],'To':['Lingampalli','Narsapur','Narsapur','Howrah']}
#creating dataframe
XII – IP 10 Record (2024.25)
Trains=pd.DataFrame(dict,index=['HydExp','NspExp', 'Pass', 'Falaknuma'])
print("1.Displaying created Dataframe...")
print(Trains)
#Display first 2 rows
print("\n2.First 2 rows using head function:\n", Trains.head(2))
print("\n2.First 2 rows using iloc function:\n", Trains.iloc[0:2])
#Display last 2 rows
print("\n3.Last 2 rows using tail function:\n", Trains.tail(2))
print("\n3.Last 2 rows using iloc function:\n", Trains.iloc[2:4])
#Display first 2 columns
print("\n4.First two columns:\n",Trains.iloc[:,0:2])
#Display the columns TrainNo and To
print("\n5.Rows - TrainNo & To:\n", Trains.iloc[:,[0,2]])
Output
1.Displaying created Dataframe...
TrainNo From To
HydExp 17255 Narsapur Lingampalli
NspExp 17256 Lingampalli Narsapur
Pass 77233 Bhimavaram Narsapur
Falaknuma 12704 Secunderabad Howrah
10. Write a program to perform the following operations on the DataFrame Object DF.
Given Data:
11. Write a program to perform the following operations on the DataFrame Object DF.
Given Data:
Name Age Class
Pavan 15 X
Kumar 16 XI
Santosh 16 XII
(1) Create the above DataFrame DF with index as ‘Stu1’,’Stu2’,’Stu3’.
Also write a statement to display it.
(2) Modify the Kumar age as 15
(3) Rename index “Stu3” to “Student3”
(4) Add the row Nani-17-XII
(5) Delete the details regarding Pavan.
Program:
#importing pandas library
import pandas as pd
#creating dataframe
dict={'Name':['Pavan','Kumar','Santosh'],'Age':[15,16,16],'Class':['X','XI','XII']}
DF=pd.DataFrame(dict,index=['Stu1','Stu2','Stu3'])
print("\n1.Created DataFrame...")
print(DF)
DF.at['Stu2','Age']=15
print("\n2.After modifying Kumar age to 15...")
print(DF)
DF.rename(index={'Stu3':'Student3'},inplace=True)
print("\n3.After Reindexing Stu3 to Student3...")
print(DF)
print("\n4.After adding Nani Details...")
DF.loc['Stu4']=['Nani',17,'XII']
print(DF)
DF.drop(["Stu1"],axis=0,inplace=True)
print("\n5.After Pavan Details Deleted...")
print(DF)
Output
1.Created DataFrame...
Name Age Class
Stu1 Pavan 15 X
Stu2 Kumar 16 XI
XII – IP 13 Record (2024.25)
Stu3 Santosh 16 XII
2.After modifying Kumar age to 15...
Name Age Class
Stu1 Pavan 15 X
Stu2 Kumar 15 XI
Stu3 Santosh 16 XII
Output
Original Dataframe.....
Teachers Students
Private 30 290
Govt 18 185
Aided 15 120
Teachers Students
Private 30 290
Govt 18 185
Aided 15 120
14. Write a program to export a dataframe to a CSV file, again import the same CSV file to a
dataframe.
Given Data:
RNo Name Marks
Sec A 15 Srinidhi 98.5
Sec B 7 Ratan 99.2
Sec C 5 Maheswari 97.3
Sec D 12 Suresh 99.5
Program:
#importing pasdas library
import pandas as pd
#creating a Dictionary
dict={'RNo':[15,7,5,12],'Name':['Srinidhi','Ratan',
'Maheswari','Suresh'],'Marks':[98.5,99.2,97.3,99.5]}
#creating a DataFrame
ExpDF=pd.DataFrame(dict,index=['Sec A','Sec B','Sec C','Sec D'])
print("Printing Created Dataframe...")
print(ExpDF)
#Exporting DataFrame to a CSV File
ExpDF.to_csv("D:/toppers.csv")
print("Dataframe ExpDF is exported CSV File")
#Importing CSV File to a DataFrame
ImpDF=pd.read_csv("D:/toppers.csv")
print("\nPrinting Imported Dataframe from a CSV File")
print(ImpDF)
Output
Printing Created Dataframe...
RNo Name Marks
Sec A 15 Srinidhi 98.5
Sec B 7 Ratan 99.2
Sec C 5 Maheswari 97.3
Sec D 12 Suresh 99.5
Dataframe ExpDF is exported CSV File
15. Write a program to export a dataframe to a CSV file, then import first 2 records from the
same CSV file to a dataframe.
Given Data:
SMarket RBazar
Brinjal 50 35
Potato 45 30
Onion 30 25
Chilly 80 55
16. Write a program for given the school result data, analyse the performance of the students
subject wise, plot using bar chart.
Given Dataframe:
Program:
import matplotlib.pyplot as plt
import pandas as pd
marks = { "English" :[45,50,48], "Maths":[65,70,55],"Physics":[75,85,52],
"Chemistry" :[45,50,53],"IP":[95,100,90]}
df = pd.DataFrame(marks, index=['Rajesh','Naveen','Sunitha'])
print("************Marksheet************")
print(df)
df.plot(kind='bar')
plt.title("Students and their Marks")
plt.xlabel("Student Names")
plt.ylabel("Marks")
plt.savefig('D:/marks.pdf')
plt.show()
XII – IP 17 Record (2024.25)
Output
17. Write a program to compare rates of vegetables in Raithubazar and Sunday Market using
line charts.
Given Data:
RBazar SMarket
Brinjal 35 50
Onion 25 35
Potato 50 40
Chilly 60 80
Program:
import matplotlib.pyplot as plt
Veg=["Brinjal","Onion","Potato","Chilly"]
RBazar=[35,25,50,60]
SMarket=[50,35,40,80]
plt.plot(Veg,RBazar,color='r')
plt.plot(Veg,SMarket,color='g')
plt.xlabel("Vegetable Names")
plt.ylabel("Vegetable Rates")
plt.title("Vegetable Rates Comparision")
plt.savefig('D:/rates.jpg')
plt.show()
Output
18. Rakesh went to Vegetables shop to purchase vegetables. Write a program to display him
vegetable names and its rates per KG using a bar chart (Give different colour to each bar).
Given Data:
Vegetable names are Brinjal, Tamota, Onion, Beetroot, Chilly
Their Corresponding Rates are 60,45,28,52,80.
XII – IP 18 Record (2024.25)
Program:
import matplotlib.pyplot as pp
vegetables=['Brinjal','Tamota','Onion','Beetroot','Chilly']
rates=[60,45,28,52,80]
pp.title ("Vegetables and their Rates")
pp.xlabel("Vegetable Names")
pp.ylabel("Vegetable Rates Per KG")
pp.bar(vegetables,rates,color=['b','red','k','g','y'])
pp.savefig('D:/veg.jpg')
pp.show()
Output
19. Plot the following data on line chart and customize chart according to below given
instructions.
Month January February March April May
Sales 500 350 450 550 600
Write a program which includes all the following:
(a) Write a title for the chart ‘The Monthly Sales Report’
(b) Write the appropriate titles of both the axes
(c) Write code to display legends
(d) Display blue color for the line
(e) Use line style-dashed
(f) Display diamond style markers on data points.
Program:
#Importing matplotlib library
import matplotlib.pyplot as pt
months=['January','February','March','April','May']
sales=[500,350,450,550,600]
#Plotting a line graph
pt.plot(months,sales,label='Sales',color='b', linestyle='dashed',marker='D')
pt.title("The Monthly Sales Report")
pt.xlabel("Months")
pt.ylabel("Sales")
pt.legend()
pt.savefig('D:/monthlysales.jpg')
#Displaying a line chart
pt.show()
XII – IP 19 Record (2024.25)
Output
21. Consider the following table “Student”. Write SQL Queries for the following:
(i) Create a student table with the student id, name, and marks as attributes where the student id is the primary key.
(ii) Insert the following details in the student table.
STUDENTID NAME MARKS
W1001 Rajesh 95
W1002 Naveen 85
W1003 Naresh 50
W1004 Sunitha 100
W1005 Lakshmi 55
(iii) Use the select command to get the details of the students with marks more than 80.
(iv) Find the min, max, sum, and average of the marks in a student marks table.
(v) To display (student ID, marks) details of the table in descending order of the marks.
(vi) To Display Name and Marks of the students whose name starts with “N”
(vii) To display the student names in lower case letters, whose marks are more than 75
(viii) To modify Lakshmi Marks to 90
(ix) Delete the details of student with studentid-W1003 in the above table.
Answers:
(i) CREATE TABLE STUDENT(STUDENTID VARCHAR(5) PRIMARY KEY,NAME VARCHAR(30),MARKS
FLOAT);
Output:
22. Consider the following table “Customers”. Write SQL Queries for the following:
(i) Create customers table with the customer ID, customer Name, country as attributes where customer id is the
primary key.
(ii) Insert the following details in the customers table.
CUSTOMER ID CUSTOMERNAME COUNTRY
C1001 Suresh India
C1002 Mohan USA
C1003 Lakshmi India
C1004 Srujana Srilanka
C1005 Rahul USA
(iii) Display CustomerName,first 3 characters from CustomerName and last 3 characters from Country.
(iv) Find the total number of customers from each country in the table using group by.
(v) To display CustomerID and CustomerName in ascending order of CustomerName.
(vi) To Display the details of the customers whose country name ends with “IA”
(vii) To display the cutomernames in upper case letters and Country names in lower case letters.
(viii) To change the Country of Mohan to Africa.
(ix) Delete the entire customers table including structure.
ANSWERS:
(i) CREATE TABLE CUSTOMERS(CUSTOMERID VARCHAR(5) PRIMARY KEY, CUSTOMERNAME
VARCHAR(30),COUNTRY VARCHAR(15));
Output:
(OR)
SELECT SUBJECT,COUNT(SUBJECT) FROM FACULTY WHERE SUBJECT='IP';
(ix) SELECT NAME FROM FACULTY WHERE SUBJECT='IP' AND SALARY=(SELECT MAX(SALARY)
FROM FACULTY);
Output:
OUTPUT
(xi)
(xii)
(xiv)
(x)