12 IP CBSE Practical File (PART-1)
12 IP CBSE Practical File (PART-1)
12 IP CBSE Practical File (PART-1)
Output Sample:
How many employees3
Enter name:sushmita
Enter salary45000
Enter name:mayank
Enter salary340
Enter name:parth
Enter salary56000
sushmita 45000
mayank 340
parth 56000
dtype: int64
Enter the name of employee whose salary needs to be changedmayank
Enter the updated salary:34000
the Series after updating the salry is
sushmita 45000
mayank 34000
parth 56000
dtype: int64
Q4. Write a program to search and display the contents of a series based on
the input given by the user. Create the series storing the AQI of various areas
of Delhi. (Take the area name as the index)
Ans4:
import pandas as pd
n=int(input("How many areas?"))
a_name=[]
aqi=[]
for i in range(n):
a=input("Enter area name:")
b=int(input("Enter AQI"))
a_name=a_name+[a]
aqi=aqi+[b]
S=pd.Series(aqi,index=a_name)
print(S)
chk=input("Enter the city whose air quality index you want to check?")
print("The AQI of ",chk, "is" ,S[chk])
Output Sample:
How many areas?4
Enter area name:dwarka
Enter AQI350
Enter area name:janakpuri
Enter AQI380
Enter area name:delhi cantt
Enter AQI276
Enter area name:chandni chowk
Enter AQI400
dwarka 350
janakpuri 380
delhi cantt 276
chandni chowk 400
dtype: int64
Enter the city whose air quality index you want to check?janakpuri
The AQI of janakpuri is 380
>>>
SECTION B:(Dataframes)
(b) Change the city of the candidate named Pooja Tyagi as Jaipur
>>> data.loc[data.name=='pooja tyagi','city']="jaipur"
>>> print(data)
name city score qualify category
12000 rishi kumar delhi 560 no gen
12001 sehdev pal noida 800 no gen
12002 simy ghosh delhi 1200 yes st
12003 pooja tyagi jaipur 900 yes sc
12004 kapil arora gurgaon 1060 yes gen
(c) Display the details of SC and ST category students.
>>> data.loc[data.category.isin(["sc","st"])]
name city score qualify category
12002 simy ghosh delhi 1200 yes st
12003 pooja tyagi jaipur 900 yes sc
>>>
(e) Display the details of candidates with the roll nos 12003 and 12004
>>> data[data.index.isin([12003,12004])]
name city score qualify category
12003 pooja tyagi jaipur 925 yes sc
12004 kapil arora gurgaon 1085 yes gen
(f) Display the name and city for all those candidates where the score is
between 800 and 1000
>>> data.loc[data.score.between(800,1000)]
name city score qualify category
12001 sehdev pal noida 825 no gen
12003 pooja tyagi jaipur 925 yes sc
Q7. Write a program to consider the dataframe created in above question
and display a menu to show the following information regarding the
dataframe.
Transpose, Column names, indexes, datatypes of individual columns,
size and shape of the dataframe. Your program must keep on displaying as
per the menu till the user’s choice.
Ans 7.
import pandas as pd
d1={'name':['rishi kumar','sehdev pal','simy ghosh','pooja tyagi','kapil arora'],
'city':['delhi','noida','delhi','gurgaon','gurgaon'],
'score':[560,800,1200,900,1060],
'qualify':['no','no','yes','yes','yes'],
'category':['gen','gen','st','sc','gen']
}
data=pd.DataFrame(d1, index=[12000,12001,12002,12003,12004])
print(data)
while(True):
print("MENU")
print("1. Display the Transpose")
print("2. Display all column names")
print("3. Display the indexes")
print("4. Display the shape")
print("5. Display the dimension")
print("6. Display the datatypes of all columns")
print("7. Display the size")
print("8. Exit")
n=int(input("Enter choice"))
if n==1:
print(data.T)
elif n==2:
print(data.columns)
elif n==3:
print(data.index)
elif n==4:
print(data.shape)
elif n==5:
print(data.ndim)
elif n==6:
print(data.dtypes)
elif n==7:
print(data.size)
elif n==8:
print("Good bye")
break
Q8 Write a program to create a menu driven program to display various sets
of records from the dataframe depending upon the choice of the user. (
Consider the dataframe named DATA)
1. display the first five rows
2. display the last five rows
3. Display any number of records from the top
4. Display any number of records from the bottom
Ans8:
import pandas as pd
d1={'name':['rishi kumar','sehdev pal','simy ghosh','pooja tyagi','kapil arora'],
'city':['delhi','noida','delhi','gurgaon','gurgaon'],
'score':[560,800,1200,900,1060],
'qualify':['no','no','yes','yes','yes'],
'category':['gen','gen','st','sc','gen']
}
data=pd.DataFrame(d1, index=[12000,12001,12002,12003,12004])
print(data)
while(True):
print("MENU")
print("1. Display the First five rows")
print("2. Display the last five rows")
print("3. Display specific number of records from the top")
print("4. Display specific number of records from the top")
print("5. Exit")
n=int(input("Enter choice"))
if n==1:
print(data.head())
elif n==2:
print(data.tail())
elif n==3:
r=int(input("Enter the number of rows from the top you want to see"))
print(data.head(r))
elif n==4:
r=int(input("Enter the number of rows from the bottom you want to
see"))
print(data.tail(r))
elif n==5:
print("Good bye")
break
Q9. Considering the given dataframe DATA, accept the roll number of the
child ( given as index) from the user and display all his details. The program
must continue executing till the user wants. The program must give a valid
output if the roll number entered for searching is not there in the dataframe.
Ans:
import pandas as pd
d1={'name':['rishi kumar','sehdev pal','simy ghosh','pooja tyagi','kapil arora'],
'city':['delhi','noida','delhi','gurgaon','gurgaon'],
'score':[560,800,1200,900,1060],
'qualify':['no','no','yes','yes','yes'],
'category':['gen','gen','st','sc','gen']
}
data=pd.DataFrame(d1, index=[12000,12001,12002,12003,12004])
print(data)
ch="y"
while(ch=='y'or ch=='Y'):
roll=int(input("Enter the roll number of the child"))
if roll in data.index:
print(data.loc[roll])
else:
print("This roll number doesnt exist")
ch=input("Do you want to search fro more candidates? [Y/N]")
Output:
Q10. Considering the above given dataframe write code to insert more
records as per the choice of the user.
Ans 10:
import pandas as pd
d1={'name':['rishi kumar','sehdev pal','simy ghosh','pooja tyagi','kapil arora'],
'city':['delhi','noida','delhi','gurgaon','gurgaon'],
'score':[560,800,1200,900,1060],
'qualify':['no','no','yes','yes','yes'],
'category':['gen','gen','st','sc','gen']
}
data=pd.DataFrame(d1, index=[12000,12001,12002,12003,12004])
print(data)
ch="y"
while(ch=='y'or ch=='Y'):
i=int(input("Enter the roll number of the candidate"))
n=input("Enter name of the cadidate")
c=input("Enter city of the candidate")
s=int(input("Enter the score"))
q=input("Enter qualify status [yes/no]")
cat=input("Enter category")
data.loc[i]=[n,c,s,q,cat]
print("The new dataframe with the added details are:")
print(data)
ch=input("Do you want to add details of more candidates? [Y/N]")
Output:
Q11.Write a menu based program to perform the following operations on
columns of the above defined dataframe based on user specified inputs:
(a) Insert a new column at the end
(b) Insert a new column at a specified position
(c) Delete a column permanantly
(d) Delete a column temporarily
(e) Display the dataframe
Ans:
import pandas as pd
d1={'name':['rishi kumar','sehdev pal','simy ghosh','pooja tyagi','kapil arora'],
'city':['delhi','noida','delhi','gurgaon','gurgaon'],
'score':[560,800,1200,900,1060],
'qualify':['no','no','yes','yes','yes'],
'category':['gen','gen','st','sc','gen']
}
data=pd.DataFrame(d1, index=[12000,12001,12002,12003,12004])
print(data)
while True:
print("MENU")
print("1. Insert a new column at the end")
print("2. Insert a new column at a specified position ")
print("3. Delete a column permanantly")
print("4. Delete a column temporarily ")
print("5. Display the dataframe")
print("6. Exit ")
ch=int(input("Enter choice"))
if ch==1:
cn=input("Enter the new column name")
det=eval(input("Enter the data of the column in the form of list"))
data[cn]=pd.Series(data=det,index=data.index)
print("Column inserted")
elif ch==2:
cn=input("Enter the new column name")
pos=int(input("enter the position where u want to insert the column"))
det=eval(input("Enter the data of the column in the form of list"))
data.insert(loc=pos-1,column=cn,value=det)
print("Column inserted")
elif ch==3:
cn=input("Enter the name of the column you want to permanantly
delete")
del data[cn]
print("Column permanantly deleted")
elif ch==4:
cn=input("Enter the name of the column you want to temporarily
delete")
data.drop(columns=cn)
print("Column temporarily deleted")
elif ch==5:
print("The Status of the current dataframe is")
print(data)
elif ch==6:
break
OUTPUT:
Sample Output:
Q13. Write a program to accept the city name and display all the participant
name and scores from that city using iterrows(). Display an appropriate
message if the city given by the user is missing.
Ans 13:
import pandas as pd
d1={'name':['rishi kumar','sehdev pal','simy ghosh','pooja tyagi','kapil arora'],
'city':['delhi','noida','delhi','gurgaon','gurgaon'],
'score':[560,800,1200,900,1060],
'qualify':['no','no','yes','yes','yes'],
'category':['gen','gen','st','sc','gen']
}
data=pd.DataFrame(d1, index=[12000,12001,12002,12003,12004])
print(data)
df.plot(kind='bar', color=['green','orange'])
plt.title("Comparison of Sales Month wise",fontsize=14,color="blue")
plt.xlabel("Month",fontsize=14,color="red")
plt.ylabel("Sales",fontsize=14,color="red")
plt.xticks(fontsize=10, rotation=30)
plt.show()
Q16. Considering the dataframe created in Q1 and present the sales of the
east region in the horizontal bar graph.
Ans:
import matplotlib.pyplot as plt
import pandas as pd
dict1={
'north':[110,150,230,400],
'east':[200,90,150,350]
}
df=pd.DataFrame(dict1, index=['April','May','june','July'])
print(df)
df['east'].plot(kind='barh', color=['green'])
plt.title("East Region Sales Month wise",fontsize=14,color="blue")
plt.xlabel("Sales",fontsize=14,color="red")
plt.ylabel("Month",fontsize=14,color="red")
plt.xticks(fontsize=10, rotation=30)
plt.show()
Q17. Number of mistakes done by 20 students in a maths objective test are
as follows: [7,10,2,1,15,4,0,3,0,8,3,4,12,12,0,0,18, 9,10,11]
To know the class performance in terms of how many students have done a
particular number of mistakes, draw a histogram with default number of
bins.
Ans:
import pandas as pd
import matplotlib.pyplot as plt
data=[7,10,2,1,15,4,0,3,0,8,3,4,12,12,0,0,18, 9,10,11]
plt.hist(data,edgecolor="black")
plt.title("Students Performance")
plt.xlabel("Range of mistakes")
plt.ylabel("Number of students(Frequency)")
plt.show()
Q18. As per the data given in Q3. draw a histogram with 3 bins.
Ans:
import pandas as pd
import matplotlib.pyplot as plt
data=[7,10,2,1,15,4,0,3,0,8,3,4,12,12,0,0,18, 9,10,11]
plt.hist(data,bins=3,edgecolor="black")
plt.title("Students Performance")
plt.xlabel("Range of mistakes")
plt.ylabel("Number of students(Frequency)")
plt.show()
Q19. As per the data given in Q3. draw a histogram with the bins defined as
0–5
5 – 10
10 – 18
18 --20
Add edgecolor and proper title and label to your chart.
Ans:
import pandas as pd
import matplotlib.pyplot as plt
data=[7,10,2,1,15,4,0,3,0,8,3,4,12,12,0,0,18, 9,10,11]
b=[0,5,10,18,20]
plt.hist(data,bins=b,edgecolor="black")
plt.title("Students Performance")
plt.xlabel("Range of mistakes")
plt.ylabel("Number of students(Frequency)")
plt.show()
Q20. Write a program in Python Pandas to create the following DataFrame
“batsman” from a Dictionary. Draw line charts to show the plotting of score1
and score 2 for all batsman. Put legends and titles. Specify different colours
and line styles of your choice for both the plotted lines. Change font size of
the titles to 15 and color to green.
B_NO Name Score1 Score2 Location
1 Sunil Pillai 90 80 Delhi
2 Gaurav Sharma 65 45 Mumbai
3 Piyush Goel 70 90 Hyderabad
4 Kartik Thakur 80 76 Delhi
Ans:
import matplotlib.pyplot as p
import pandas as pd
dict1={'name':['sunil pillai','gaurav sharma','piyush goel','kartik thakur'],
'score1':[90,65,70,80],
'score2':[80,45,90,76],
'location':['delhi','mumbai','hyderabad','delhi']}
df=pd.DataFrame(dict1,index=[1,2,3,4])
print(df)
x=df['name']
y=df['score1']
z=df['score2']
p.plot(x,y, linestyle="-",label="Score 1")
p.plot(x,z, linestyle=":",label="Score 2")
p.title('Presenting Cricket scores for every batsman')
p.xlabel('Name of Batsman',fontsize="14",color="green")
p.ylabel('Scores',fontsize="14",color="green")
p.legend()
p.show()