0% found this document useful (0 votes)
29 views26 pages

XII-IP-Record (2024.25)

Uploaded by

chirag79848
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)
29 views26 pages

XII-IP-Record (2024.25)

Uploaded by

chirag79848
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/ 26

XII – IP RECORD (2024.

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

1.Series after modifying the Carrot value..


Beetroot 40
Carrot 90
Drumstick 10
Brinjal 50
dtype: int64

2.Series after adding Tomato details..


Beetroot 40
Carrot 90
Drumstick 10
Brinjal 50
Tomato 30
dtype: int64

3.Series After modifying Brinjal index


Beetroot 40
Carrot 90
Drunstick 10
PennadaBrinjal 50
Tomato 30
dtype: int64

4.Fetching first 3 rows using Head function


Beetroot 40
Carrot 90
Drunstick 10
dtype: int64

5.Fetching last 4 rows using Tail function


Carrot 90
Drunstick 10
PennadaBrinjal 50
Tomato 30
dtype: int64
4. Write a program to perform the following operations on the 2 Series Objects
‘Week1’ and ‘Week2’
Given Data:

Index Data
Sun 100
Mon 150
Tue 120
Wed 130
Thu 155
Fri 160
Sat 190
Week1

XII – IP 3 Record (2024.25)


Index Data
Sun 70
Mon 80
Tue 90
Wed 95
Thu 85
Fri 75
Sat 98
Week2
1. Create a Series Week1 (Sales of bananas in Week1)
2. Create a Series Week2 (Sales of bananas in Week2)
3. Create a Series "Total" with total sales of two weeks
4. Change the Week 1 - Wednesday Sales Details Value to 30.
5. Show the Week 2 - Tuesday to Friday Sales Details using Slicing
6. Change the sat index of Week 2 to Saturday.
Program:
import pandas as pd
Daynames=["Sun","Mon","Tue","Wed","Thu", "Fri","Sat"]
W1sales=[100,150,120,130,155,160,190]
W2sales=[70,80,90,95,85,75,98]
Week1=pd.Series(data=W1sales,index=Daynames)
Week2=pd.Series(data=W2sales,index=Daynames)
print("\n1.Series Object - Week1 :\n",Week1)
print("\n2.Series Object - Week2 :\n",Week2)
Total=Week1+Week2
print("\n3. Series Object - Total :\n",Total)
Week1["Wed"]=250
print("\n4. Week1 Details after modifying Wednesday Sales \n",Week1)
print("\n5. Week2 - Tuesday to Friday Details:\n",Week2[2:6])
Week2.rename(index={"Sat":"Saturday"},inplace=True)
print("\n6. Week2 - After changing Sat to Saturday:\n",Week2)
OUTPUT
1.Series Object - Week1 :
Sun 100
Mon 150
Tue 120
Wed 130
Thu 155
Fri 160
Sat 190
dtype: int64

2.Series Object - Week2 :


Sun 70
Mon 80
Tue 90
Wed 95
Thu 85
Fri 75
Sat 98
dtype: int64

3. Series Object - Total :


Sun 170
Mon 230
XII – IP 4 Record (2024.25)
Tue 210
Wed 225
Thu 240
Fri 235
Sat 288
dtype: int64

4. Week1 Details after modifying Wednesday Sales


Sun 100
Mon 150
Tue 120
Wed 250
Thu 155
Fri 160
Sat 190
dtype: int64

5. Week2 - Tuesday to Friday Details:


Tue 90
Wed 95
Thu 85
Fri 75
dtype: int64

6. Week2 - After changing Sat to Saturday:


Sun 70
Mon 80
Tue 90
Wed 95
Thu 85
Fri 75
Saturday 98
dtype: int64
5. Write a program to create the following two Series Objects ‘S1’ and ‘S2’.
S1 S2
10 1
20 2
30 3
40 4
(1) Create the above 2 series objects and display it.
(2) Perform Arithmetic Addition Operation (S1+S2)
(3) Perform Arithmetic Subtraction Operation (S1-S2)
(4) Perform Arithmetic Multiplication Operation (S1*S2)
(5) Perform Arithmetic Division Operation (S1/S2)
Also write the outputs.
Program:
#importing pandas library
import pandas as pd
S1=pd.Series([10,20,30,40])
S2=pd.Series([1,2,3,4])
print("1.Displaying Series 1.....")
print(S1)
print("\n Displaying Series 2.....")
print(S2)
print("\n2.Displaying Series 1 + Series 2...Arithmetic Addition")
print(S1+S2)

XII – IP 5 Record (2024.25)


print("\n3.Displaying Series 1 - Series 2...Arithmetic Subtraction")
print(S1-S2)
print("\n4.Displaying Series 1 X Series 2...Arithmetic Multiplication")
print(S1*S2)
print("\n5.Displaying Series 1 / Series 2...Arithmetic Division")
print(S1/S2)
Output
1.Displaying Series 1.....
0 10
1 20
2 30
3 40
dtype: int64

Displaying Series 2.....


0 1
1 2
2 3
3 4
dtype: int64

2.Displaying Series 1 + Series 2...Arithmetic Addition


0 11
1 22
2 33
3 44
dtype: int64
3.Displaying Series 1 - Series 2...Arithmetic Subtraction
0 9
1 18
2 27
3 36
dtype: int64

4.Displaying Series 1 X Series 2...Arithmetic Multiplication


0 10
1 40
2 90
3 160
dtype: int64

5.Displaying Series 1 / Series 2...Arithmetic Division


0 10.0
1 10.0
2 10.0
3 10.0
dtype: float64

6. Write a Program to create


(a) A Dataframe DF1 using Dictionary having values as lists and display it
Pavan Srinu Sunitha
Telugu 56 90 78
English 75 91 64
Maths 82 98 96
Science 72 92 88
Social 68 85 76
DF1
(b) Add a new Row with index “Hindi” with values 79,89 and 99 in DF1
XII – IP 6 Record (2024.25)
(c) A Dataframe DF2 using a list having list of lists
SNo BookName Price
One 1 C++ 550
Two 2 Python 625
Three 3 Java 525
Four 4 C 400
DF2
(d) Delete row with index “Three” from DF2.
Program:
#importing pandas library
import pandas as pd
#Creating a Dataframe DF1 using 2-D Dictionary having values as lists
marks={'Pavan':[56,75,82,72,68],'Srinu':[90,91,98,92,85], 'Sunitha':[78,64,96,88,76]}
DF1=pd.DataFrame(marks,index=['Telugu','English','Maths','Science','Social'])
print("Displaying Dataframe DF1.....")
print(DF1)
DF1.loc["Hindi"]=79,89,99
print("\nDataframe DF1 after adding Hindi Details...\n",DF1)
#Creating a Dataframe DF2 using a list having list of lists
books=[[1,'C++',550],[2,'Python',625],[3,'Java',525],[4,'C',400]]
#each inner list is a row
DF2=pd.DataFrame(books,columns=['SNo','BookName','Price'],index=['One','Two','Three','Four'])
print("\nDisplaying Dataframe DF2.....")
print(DF2)
#Delete row with index “Three” from DF2.
DF2.drop('Three',inplace=True)
print("\nDataframe DF2 after removing Three Details...\n",DF2)
Output
Displaying Dataframe DF1.....
Pavan Srinu Sunitha
Telugu 56 90 78
English 75 91 64
Maths 82 98 96
Science 72 92 88
Social 68 85 76
Dataframe DF1 after adding Hindi Details...
Pavan Srinu Sunitha
Telugu 56 90 78
English 75 91 64
Maths 82 98 96
Science 72 92 88
Social 68 85 76
Hindi 79 89 99
Displaying Dataframe DF2.....
Sno BookName Price
One 1 C++ 550
Two 2 Python 625
Three 3 Java 525
Four 4 C 400
Dataframe DF2 after removing Three Details...
SNo BookName Price
One 1 C++ 550
Two 2 Python 625
Four 4 C 400
XII – IP 7 Record (2024.25)
7. Create the following dataframe for examination result and display it.
Given Data:
Pavan Srinu Sunitha
Telugu 56 90 78
English 75 91 64
Maths 82 98 96
Science 72 92 88
Social 68 85 76
Also perform the following:
(1) Create the dataframe and display it
(2) Display row labels
(3) Display column labels
(4) Display data types of each column
(5) Display dimension of dataframe
(6) Display Transpose of dataframe
(7) Display Shape of the Dataframe
Program:
#importing pandas library
import pandas as pd
#Creating a Dataframe DF1 using 2-D Dictionary having values as lists
marks={'Pavan':[56,75,82,72,68],'Srinu':[90,91,98,92,85], 'Sunitha':[78,64,96,88,76]}
df=pd.DataFrame(marks,index=['Telugu','English','Maths','Science','Social'])
print("\n1.Displaying DataFrame: ")
print(df)
print("\n2.Displaying Row labels: ")
print(df.index)
print("\n3.Displaying Column labels: ")
print(df.columns)
print("\n4.Displaying Datatypes of each column")
print("---------------------------------")
print(df.dtypes)
print("\n5.Displaying Dimension of Dataframe")
print("--------------------------------")
print(df.ndim)
print("\n6.Displaying Transpose of the Dataframe")
print("--------------------------------")
print(df.T)
print ("\n7.Shape of the Dataframe")
print(df.shape)
Output
1.Displaying DataFrame:
Pavan Srinu Sunitha
Telugu 56 90 78
English 75 91 64
Maths 82 98 96
Science 72 92 88
Social 68 85 76

2.Displaying Row labels:


Index(['Telugu', 'English', 'Maths', 'Science', 'Social'], dtype='object')

3.Displaying Column labels:


Index(['Pavan', 'Srinu', 'Sunitha'], dtype='object')

XII – IP 8 Record (2024.25)


4.Displaying Datatypes of each column
---------------------------------
Pavan int64
Srinu int64
Sunitha int64
dtype: object

5.Displaying Dimension of Dataframe


--------------------------------
2

6.Displaying Transpose of the Dataframe


--------------------------------
Telugu English Maths Science Social
Pavan 56 75 82 72 68
Srinu 90 91 98 92 85
Sunitha 78 64 96 88 76

7.Shape of the Dataframe


(5, 3)

8. Consider the following Dataframe “Veg”.


RBazar SMarket
Brinjal 40 70
Onion 30 35
Carrot 60 80
Chilly 50 65
Do the following operations:
(1) Create the dataframe and display it
(2) Display first two vegetables details
(3) Display last 3 vegetable details
(4) Change RBazar rate of Brinjal to 25
(5) Change “RBazar” to “RaithuBazar”, “SMarket” to “SundayMarket”.
Program:
#importing pandas library
import pandas as pd
#creating dictionary
dict={'RBazar':[40,30,60,50],'SMarket':[70,35,80,65]}
Veg=pd.DataFrame(dict,index=['Brinjal','Onion','Carrot','Chilly'])
print("\n1.Displaying created dataframe....")
print(Veg)
print("\n2.First 2 vegetable details using head function:\n",Veg.head(2))
print("\n2.First 2 vegetable details using iloc function:\n",Veg.iloc[0:2])
print("\n3.Last 3 vegetable details using tail function:\n",Veg.tail(3))
print("\n3.Last 3 vegetable details using iloc function:\n",Veg.iloc[1:4])
Veg.at['Brinjal','RBazar']=25
print("\n4.After modifying Brinjal Rate at Raithu Bazar to 25...\n", Veg)
Veg.rename(columns={'RBazar':'RaithuBazar','SMarket':'SundayMarket'},inplace=True)
print("\n5.After modifying Column labels...\n", Veg)
Output
1.Displaying created dataframe....
RBazar SMarket
Brinjal 40 70
Onion 30 35
XII – IP 9 Record (2024.25)
Carrot 60 80
Chilly 50 65

2.First 2 vegetable details using head function:


RBazar SMarket
Brinjal 40 70
Onion 30 35

2.First 2 vegetable details using iloc function:


RBazar SMarket
Brinjal 40 70
Onion 30 35

3.Last 3 vegetable details using tail function:


RBazar SMarket
Onion 30 35
Carrot 60 80
Chilly 50 65
3.Last 3 vegetable details using iloc function:
RBazar SMarket
Onion 30 35
Carrot 60 80
Chilly 50 65

4.After modifying Brinjal Rate at Raithu Bazar to 25...


RBazar SMarket
Brinjal 25 70
Onion 30 35
Carrot 60 80
Chilly 50 65

5.After modifying Column labels...


RaithuBazar SundayMarket
Brinjal 25 70
Onion 30 35
Carrot 60 80
Chilly 50 65

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

2.First 2 rows using head function:


TrainNo From To
HydExp 17255 Narsapur Lingampalli
NspExp 17256 Lingampalli Narsapur

2.First 2 rows using iloc function:


TrainNo From To
HydExp 17255 Narsapur Lingampalli
NspExp 17256 Lingampalli Narsapur

3.Last 2 rows using tail function:


TrainNo From To
Pass 77233 Bhimavaram Narsapur
Falaknuma 12704 Secunderabad Howrah
3.Last 2 rows using iloc function:
TrainNo From To
Pass 77233 Bhimavaram Narsapur
Falaknuma 12704 Secunderabad Howrah

4.First two columns:


TrainNo From
HydExp 17255 Narsapur
NspExp 17256 Lingampalli
Pass 77233 Bhimavaram
Falaknuma 12704 Secunderabad

5.Rows - TrainNo & To:


TrainNo To
HydExp 17255 Lingampalli
NspExp 17256 Narsapur
Pass 77233 Narsapur
Falaknuma 12704 Howrah

10. Write a program to perform the following operations on the DataFrame Object DF.
Given Data:

XII – IP 11 Record (2024.25)


Eno Ename Designation
1 Nagur Clerk
2 Swetha Manager
3 Vani Clerk
(1) Create the above DataFrame DF with index as ‘One’,’Two’,’Three’.
Also write a statement to display it.
(2) Display EName and Designation Details
(3) Display Row Details with “Three” index
(4) Change Designation of Nagur to “CEO”
(5) Change row index “One” to “First”
(6) Add a new Employee with row index “Four”. Details - 4,Mukesh, Clerk
(7) Delete “Swetha” Details
Program:
#importing pandas library
import pandas as pd
#creating dataframe
dict={'ENo':[1,2,3],'EName':['Nagur','Swetha','Vani'],'Designation':['Clerk','Manager','Clerk']}
DF=pd.DataFrame(dict,index=['One','Two','Three'])
print("\n1.Created DataFrame...")
print(DF)
print("\n2.Displaying EName and Designation Details...\n",DF[['EName','Designation']])
print("\n3.Displaying Row Details with Three index....\n",DF.loc["Three"])
DF.at['One','Designation']="CEO"
print("\n4.After modifying Designation of Nagur to CEO...")
print(DF)
DF.rename(index={'One':'First'},inplace=True)
print("\n5.After Reindexing One to First...")
print(DF)
print("\n6.After adding Mukesh Details...")
DF.loc['Four']=[4,'Mukesh','Clerk']
print(DF)
DF.drop(["Two"],axis=0,inplace=True)
print("\n7.After Swetha Details Deleted...")
print(DF)
Output
1.Created DataFrame...
ENo EName Designation
One 1 Nagur Clerk
Two 2 Swetha Manager
Three 3 Vani Clerk

2.Displaying EName and Designation Details...


EName Designation
One Nagur Clerk
Two Swetha Manager
Three Vani Clerk

3.Displaying Row Details with Three index....


ENo 3
EName Vani
Designation Clerk
Name: Three, dtype: object

4.After modifying Designation of Nagur to CEO...


ENo EName Designation
One 1 Nagur CEO
Two 2 Swetha Manager
Three 3 Vani Clerk

XII – IP 12 Record (2024.25)


5.After Reindexing One to First...
ENo EName Designation
First 1 Nagur CEO
Two 2 Swetha Manager
Three 3 Vani Clerk
6.After adding Mukesh Details...
ENo EName Designation
First 1 Nagur CEO
Two 2 Swetha Manager
Three 3 Vani Clerk
Four 4 Mukesh Clerk

7.After Swetha Details Deleted...


ENo EName Designation
First 1 Nagur CEO
Three 3 Vani Clerk
Four 4 Mukesh Clerk

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

3.After Reindexing Stu3 to Student3...


Name Age Class
Stu1 Pavan 15 X
Stu2 Kumar 15 XI
Student3 Santosh 16 XII

4.After adding Nani Details...


Name Age Class
Stu1 Pavan 15.0 X
Stu2 Kumar 15.0 XI
Student3 Santosh 16.0 XII
Stu4 Nani 17.0 XII

5.After Pavan Details Deleted...


Name Age Class
Stu2 Kumar 15.0 XI
Student3 Santosh 16.0 XII
Stu4 Nani 17.0 XII
12. Write a program which iterates rows in a dataframe.
Given Data:
Teachers Students
Private 30 290
Govt 18 185
Aided 15 120
Program:
#importing pandas library
import pandas as pd
#creating a Dictionary
dict={'Teachers':[30,18,15],'Students':[290,185,120]}
#creating a DataFrame
DF=pd.DataFrame(dict,index=['Private','Govt','Aided'])
print("Original Dataframe.....")
print(DF)
print("\nIterating rows over Dataframe:")
print("---------------")
for (row,rowSeries) in DF.iterrows():
print("\nRow index:",row)
print("Containing: ")
print(rowSeries)

Output
Original Dataframe.....
Teachers Students
Private 30 290
Govt 18 185
Aided 15 120

Iterating rows over Dataframe:


---------------

XII – IP 14 Record (2024.25)


Row index: Private
Containing:
Teachers 30
Students 290
Name: Private, dtype: int64

Row index: Govt


Containing:
Teachers 18
Students 185
Name: Govt, dtype: int64

Row index: Aided


Containing:
Teachers 15
Students 120
Name: Aided, dtype: int64

13. Write a program which iterates columns in a dataframe.


Given Data:
Teachers Students
Private 30 290
Govt 18 185
Aided 15 120
Program:
#importing pandas library
import pandas as pd
#creating a Dictionary
dict={'Teachers':[30,18,15],'Students':[290,185,120]}
#creating a DataFrame
DF=pd.DataFrame(dict,index=['Private','Govt','Aided'])
print("Original Dataframe....")
print(DF)
print("\nIterating columns over Dataframe:")
print("------------------")
for (col,colSeries) in DF.items(): #(or) in DF.iteritems()
print("\nColumn index:",col)
print("Containing: ")
print(colSeries)
Output
Original Dataframe....

Teachers Students
Private 30 290
Govt 18 185
Aided 15 120

Iterating columns over Dataframe:


------------------
Column index: Teachers
Containing:
Private 30
Govt 18
Aided 15
Name: Teachers, dtype: int64

Column index: Students


XII – IP 15 Record (2024.25)
Containing:
Private 290
Govt 185
Aided 120
Name: Students, dtype: int64

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

Printing Imported Dataframe from a CSV File


Unnamed: 0 RNo Name Marks
0 Sec A 15 Srinidhi 98.5
1 Sec B 7 Ratan 99.2
2 Sec C 5 Maheswari 97.3
3 Sec D 12 Suresh 99.5

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

XII – IP 16 Record (2024.25)


Program:
#importing pasdas library
import pandas as pd
#creating a Dictionary
dict={'SMarket':[50,45,30,80],'RBazar':[35,30,25,55]}
#creating a DataFrame
ExpDF=pd.DataFrame(dict,index=['Brinjal', 'Potato','Onion','Chilly'])
print("Printing Created Dataframe...")
print(ExpDF)
#Exporting DataFrame to a CSV File
ExpDF.to_csv("D:/vegetables.csv")
print("Dataframe ExpDF is exported CSV File")
#Importing CSV File to a DataFrame
ImpDF=pd.read_csv("D:/vegetables.csv",nrows=2)
print("\nPrinting Imported Dataframe from a CSV File")
print(ImpDF)
Output
Printing Created Dataframe...
SMarket RBazar
Brinjal 50 35
Potato 45 30
Onion 30 25
Chilly 80 55
Dataframe ExpDF is exported CSV File
Printing Imported Dataframe from a CSV File
Unnamed: 0 SMarket RBazar
0 Brinjal 50 35
1 Potato 45 30

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

20. Plot the following ages details of 20 students using Histogram.


X=[16,15,14,18,17,16,14,16,15,18,15,16,18,14,16,15,14,16,17,14]
Program:
#Importing matplotlib library
import matplotlib.pyplot as pl
X=[16,15,14,18,17,16,14,16,15,18,15,16,18,14,16,15,14,16,17,14]
#Plotting a histogram with edge color red
pl.hist(X,ec='red')
#Displaying title of the graph
pl.title("Histogram showing Countwise Ages in a Inter College of 20 students")
#Displaying X axis label
pl.xlabel("Ages")
#Displaying Y axis label
pl.ylabel("Count")
pl.savefig('D:/ageshistogram.pdf')
#Displaying histogram
pl.show()
Output

XII – IP 20 Record (2024.25)


SQL RECORD PROGRAMS : 21 to 23

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:

(ii) INSERT INTO STUDENT VALUES('W1001','Rajesh',95),('W1002','Naveen',85), ('W1003','Naresh',50),


('W1004','Sunitha',100),('W1005','Lakshmi','55');
Output:

(iii) SELECT * FROM STUDENT WHERE MARKS>80;


Output:

(iv) SELECT MIN(MARKS),MAX(MARKS),SUM(MARKS),AVG(MARKS) FROM STUDENT;


Output:

(v) SELECT STUDENTID,MARKS FROM STUDENT ORDER BY MARKS DESC;


Output:

(vi) SELECT NAME,MARKS FROM STUDENT WHERE NAME LIKE "N%";


Output:

XII – IP 21 Record (2024.25)


(vii) SELECT LCASE(NAME) FROM STUDENT WHERE MARKS>75
Output:

(viii) UPDATE STUDENT SET MARKS=90 WHERE NAME='LAKSHMI';


Output:

(ix) DELETE FROM STUDENT WHERE STUDENTID='W1003';


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:

(ii) INSERT INTO CUSTOMERS VALUES('C1001','Suresh','India'),('C1002','Mohan','USA'),


('C1003','Lakshmi','India'),('C1004','Srujana','Srilanka'),('C1005','Rahul','USA');
Output:

XII – IP 22 Record (2024.25)


(iii) SELECT CUSTOMERNAME, LEFT(CUSTOMERNAME,3),RIGHT(COUNTRY,2) FROM CUSTOMERS;
Output:

(iv) SELECT COUNTRY,COUNT(*) FROM CUSTOMERS GROUP BY COUNTRY;


Output:

(v) SELECT CUSTOMERID,CUSTOMERNAME FROM CUSTOMERS ORDER BY CUSTOMERNAME ASC;


Output:

(vi) SELECT * FROM CUSTOMERS WHERE COUNTRY LIKE "%ia";


Output:

(vii) SELECT UCASE(CUSTOMERNAME), LCASE(COUNTRY) FROM CUSTOMERS;


Output:

(viii) UPDATE CUSTOMERS SET COUNTRY="AFRICA" WHERE CUSTOMERNAME="MOHAN";


Output:

(ix) DROP TABLE CUSTOMERS;


Output:

XII – IP 23 Record (2024.25)


23. Consider the following table “Faculty”.
SNo Name Subject DOJ Salary
1 Naveen Babu IP 2019-12-25 65759
2 Suman Suresh ICT 2015-10-18 53460
3 Swathi Latha AI 2020-05-10 62724
4 Gayathri Kumari IP 2020-03-15 45690
Write SQL Queries for the following:
(i) To create the above table.
(ii) To make SNo as Primary Key
(iii) To insert the above values in to the table.
(iv) To get the number of count to each character in every name;
(v) To display the name of the person who have joined recently;
(vi) To display the name of the month joined by Naveen Babu
(vii) To count the number of persons who are teaching subject IP
(viii) To display the total salary of all the employees;
(ix) To display the name of the person who is teaching subject IP and getting more salary.
(x) To display names of the faculty along with their year of joining.
Write outputs for the following SQL Queries:
(xi) SELECT NAME,POWER(SNO,3) FROM FACULTY;
(xii) SELECT NAME,SALARY,ROUND(SALARY,-2) FROM FACULTY;
(xiii) SELECT MOD(SALARY,SNO) FROM FACULTY;
(xiv) SELECT MID(RIGHT(NAME,4),2) FROM FACULTY;
(xv) SELECT INSTR(NAME,’A’) FROM FACULTY;
ANSWERS:
(i) CREATE TABLE FACULTY(SNO INT,NAME VARCHAR(20),SUBJECT VARCHAR(10),DOJ
DATE,SALARY INT);
Output:

(ii) ALTER TABLE FACULTY ADD PRIMARY KEY(SNO);


Output:

(iii) INSERT INTO FACULTY VALUES(1,'Naveen Babu','IP','2019-12-25',65759),(2,'Suman Suresh','ICT','2015-


10-18',53460),(3,'Swathi Latha','AI','2020-05-10',62724),(4,'Gayathri Kumari','IP','2020-03-15',45690);
Output:

(iv) SELECT NAME,LENGTH(NAME) FROM FACULTY;


Output:

XII – IP 24 Record (2024.25)


(v) SELECT NAME FROM FACULTY WHERE DOJ= (SELECT MAX(DOJ) FROM FACULTY);
Output:

(vi) SELECT MONTHNAME(DOJ) FROM FACULTY WHERE NAME='Naveen Babu';


Output:

(vii) SELECT SUBJECT,COUNT(*) FROM FACULTY GROUP BY SUBJECT HAVING SUBJECT='IP';


Output:

(OR)
SELECT SUBJECT,COUNT(SUBJECT) FROM FACULTY WHERE SUBJECT='IP';

(viii) SELECT SUM(SALARY) AS "TOTAL SALARY OF ALL EMPLOYEES" FROM FACULTY;


Output:

(ix) SELECT NAME FROM FACULTY WHERE SUBJECT='IP' AND SALARY=(SELECT MAX(SALARY)
FROM FACULTY);
Output:

(x) SELECT NAME,YEAR(DOJ) FROM FACULTY;


Output:

OUTPUT
(xi)

(xii)

XII – IP 25 Record (2024.25)


(xiii)

(xiv)

(x)

XII – IP 26 Record (2024.25)

You might also like