PROGRAMMING QUESTIONS:
PROGRAM 1) Write code to create a Series object that stores the initial budget allocated for the five MONTHS of the year :
Month1 50000
Month2 56000
Month3 76000
Month4 72000
Month5 80000
Also write the commands to
[1] Display the first two values from the above series.
[2] Display the last three values from the above series.
[3] Display the indexes of the series
[4] change the indexes to jan, feb, mar, apr, may
[5] arrange the series in descending order of values and display it.
ANSWER:
import pandas as pd
budget=[50000,56000,76000,72000,80000]
mon=['Month1','Month2','Month3','Month4','Month5']
ser1=pd.Series(budget,index=mon)
print(ser1)
print("First two values \n",ser1.head(2))
print("Last three values \n",ser1.tail(3))
ser1.index=[ 'jan','feb',' mar',' apr',' may']
print('\n series with new indexes=\n',ser1)
print("Series in descending order")
ser2=ser1.sort_values(ascending=False)
print(ser2)
PROGRAM 2)Write code to create Series objects from lists named
Acc,BSt,Eco,Eng,IP containing marks of 5 students in five subjects.
Acc 45 67 80 56 34
BSt 65 70 76 92 95
Eco 80 67 45 46 74
Eng 75 57 89 95 99
IP 89 78 87 90 98
Assign the index as RollNo1, RollNo2, RollNo3, RollNo4, RollNo5.
Create series objects containing the total and average marks and
display it.
import pandas as pd
Acc=[45,67,80,56,34]
BSt=[65,70,76,92,95]
Eco=[80,67,45,46,74]
Eng=[75,57,89,95,99]
IP=[89,78,87,90,98]
rn=['RollNo1','RollNo2','RollNo3','RollNo4','RollNo5']
ser1=pd.Series(Acc, index=rn)
ser2=pd.Series(BSt,index=rn)
ser3=pd.Series(Eco,index=rn)
ser4=pd.Series(Eng,index=rn)
ser5=pd.Series(IP,index=rn)
print(ser1,'\n',
ser2,'\n',
ser3,'\n',
ser4,'\n',
ser5,'\n')
tot=ser1+ser2+ser3+ser4+ser5
tot.index=rn #find total
print("Total marks of the students")
print(tot)
av=tot/5 #find average
av.index=rn
print("Average marks of the students")
print(av)
PROGRAM 3)Create and display a series P1 containing prices of 6 stationery items as given below :
Pencils 20
Notebooks 45
Scales 15
Erasers 10
Paint brush 75
Sketch pens 240
The names will become indices of the series P1.
Create and display another series P2 containing quantity of the 6 items.
Pencils 52
Notebooks 45
Scales 15
Erasers 10
Paint brush 22
Sketch pens 40
Now create and display a series TOTAL that contains total price as price*qty.
Display the second , third,fourth values from the total series.
Display first and last values from total series using index labels.
ANSWER-3-
import pandas as pd
Stationery=['Pencils','Notebooks','Scales','Erasers','Paint brush','Sketch pens']
P1=pd.Series([20,45,15,10,75,240],index=Stationery)
P2=pd.Series([52,45,15,10,22,40],index=Stationery)
print("Prices of stationery items")
print(P1)
print("Quantity of stationery items")
print(P2)
TOTAL=P1*P2
print("Total prices of stationery items")
print(TOTAL)
print("Second,third,fourth items are:-")
print(TOTAL[1:4])
print("first and last items using index labels are:-")
print(TOTAL[['Pencils','Sketch pens']])
PROGRAM 4) Consider two series objects staff and salaries that store the number of no. of people in 6 office branches and salaries distributed in these branches respectively.
Staff Salaries
B1 20 B1 279000
B2 36 B2 396800
B3 44 B3 563000
B4 102 B4 485000
B5 25 B5 780900
B6 80 B6 865000
Write codes to:-
Create the above series.
Display data of salary above 500000 from the series.
Create another Series object that stores average salary per branch and then create a DataFrame object from these Series objects.
#PROGRAM-4
import pandas as pd
import numpy as np
I=['B1','B2','B3','B4','B5','B6']
staff=pd.Series([20,36,44,102,25,80],index=I)
sal= pd.Series([279000,396800,563000,485000,780900,865000],index=I)
print("STAFF ARE:-")
print(staff)
print("SALARIES ARE...")
print(sal)
print("salaries above 500000 are...")
print(sal[sal>500000])
avg= sal/ staff
#creating dataframe from above series
org={'people':staff,'Amount': sal ,'Average':avg}
dt1=pd.DataFrame(org)
print(dt1)
PROGRAM 5) Write a program to create a dataframe from a list containing dictionaries of the sales performance of four zonal offices.
[{‘Target’:56000,’Sales’:58000},{‘Target’:76000,’Sales’:48000} , {‘Target’:32000,’Sales’:65000}, {‘Target’:52000,’Sales’:84000}]
Zone names (zoneA,zoneB,zoneC,zoneD) should be the row labels.
Add a new column City with values as “New Delhi”
Rename the column Target as New_Target
Display the total and average sale of all the four zones.
#PROGRAM-5
import pandas as pd
zoneA={'Target':56000,'Sales':58000}
zoneB={'Target':76000,'Sales':48000}
zoneC={'Target':32000,'Sales':65000}
zoneD={'Target':52000,'Sales':84000}
sales=[zoneA,zoneB,zoneC,zoneD]
saleDf=pd.DataFrame(sales,index= ['zoneA','zoneB','zoneC','zoneD'])
print(saleDf)
#ADDING NEW COLUMN CITY
saleDf['City']='New Delhi'
print(saleDf)
#RENAMING THE COLUMN TARGET
saleDf.rename(columns={'Target':'New_Target'} ,inplace=True)
print(saleDf)
s=sum(saleDf['Sales'])
av=s/4
print("sum of sales of all zones=",s)
print("average of sales of all zones=",av)
PROGRAM 6) Create and display a DataFrame from a 2D dictionary , Emp , which stores the salary of 4 employees as inner dictionary for four years, as shown below:
Sal={‘year1’:{‘E101’:34500, ‘E102’:56000, ‘E103′:47000,’E104’:49000},
‘year2’:{‘E101’:38500, ‘E102’:58000, ‘E103′:58500,’E104’:55000},
‘year3’:{‘E101’:52000, ‘E102’:66000, ‘E103′:63500,’E104’:62000},
‘year4’:{‘E101’:61000, ‘E102’:69000, ‘E103′:69500,’E104’:71000}}
Display data of those employees whose sales is below 56000 in second year.
Add a new row containing details of year5
Change the data of E101 as [35000,45000,53000,62000]
Display the salary of all employees in first year
ANSWER:
#PROGRAM-6
import pandas as pd
Sal={'year1':{'E101':34500, 'E102':56000, 'E103':47000,'E104':49000},
'year2':{'E101':38500, 'E102':58000, 'E103':58500,'E104':55000},
'year3':{'E101':52000, 'E102':66000, 'E103':63500,'E104':62000},
'year4':{'E101':61000, 'E102':69000, 'E103':69500,'E104':71000}}
dfsales=pd.DataFrame(Sal)
print(dfsales)
dt1=dfsales[dfsales['year2']<56000]
print("Data of employees whose sales is below 56000 in second year")
print(dt1['year2'])
print("NEW ROW ADDED")
dfsales.loc['E105']=[55500,57000,65000,78000]
print(dfsales)
print("CHANGES DONE IN ROW 1")
dfsales.loc['E101']= [35000,45000,53000,62000]
print(dfsales)
print("SALARY IN FIRST YEAR")
print(dfsales['year1'])
PROGRAM 7) Consider the following dataframe student:
Rno Name Fees Class
Id1 1001 Gauri 5000 11A
Id2 1002 Geetika 6000 12A
Id3 1003 Mishti 5000 11B
Id4 1004 Kavya 6000 12B
Id5 1050 Meeta 3600 10A
a. Write code to create above dataframe
b. Write a code to change the data of id3 with (1005,Priya,8000,12B)
c. Write code to change the rno of id1 with 1015.
d. Write code to display values of two columns name and fees only
e. Write code to display details of last three students
f. Write code to display Rno, name of first, third and fourth student
#program=7
import pandas as pd
d1={'Rno':[ 1001,1002,1003,1004,1050],
'Name':[ 'Gauri','Geetika','Mishti','Kavya','Meeta'],
'Fees':[ 5000,6000,5000,6000,3600],
'Class':[ '11A','12A','11B','12B','10A']}
student=pd.DataFrame(d1,index=['Id1','Id2','Id3','Id4','Id5'])
print("Values of dataframe student")
print(student)
print("After changing the values of id3")
student.iloc[2]=[ 1005,'Priya',8000,'12B']
print(student)
print("After changing the rno of id1")
student.iat[0,0]=1015
print(student)
print("Values of name and fees column")
print(student.loc[:,'Name':'Fees'])
print("details of last three students")
print(student.tail(3))
print("Rno, name of first, third and fourth student")
print(student.loc[['Id1','Id3','Id4'],[ 'Rno','Name']])
PROGRAM 8) Consider the following dataframe Item
Fcode Fname Price
Nestle F01 Chocolate 50
Parle F02 Biscuit 45
Britannia F03 Biscuit 30
Cremica F04 Biscuits 40
Amul F05 Chocolate 70
a. Write a program to create a dataframe Item as given above.
b. Add a column orders having values 500,600,700,340,450 respectively.
c. To add a new row as ‘Unibic’=[‘F05′,’Chocolate’,50,370]
d. To display the content of last two rows.
e. To modify the price of Nestle as 60
#PROGRAM-8
data={'Fcode':['F01','F02','F03','F04','F05'],
'Fname':['Chocolate','Biscuit','Biscuit','Biscuits','Chocolate'],
'Price':[50,45,30,40,70]}
i=['Nestle','Parle','Britannia','Cremica','Amul']
Item=pd.DataFrame(data,index=i)
print("Values of dataframe Item")
print(Item)
print("After adding column orders")
Item['orders']=[500,600,700,340,450]
print(Item)
print("After adding a new row")
Item.loc['Unibic',:]=['F05','Chocolate',50,370]
print(Item)
print("The content of last two rows")
print(Item.iloc[2:])
print("Modify the price of Nestle as 60")
Item.iloc[0,2]=60
print(Item)
PROGRAM 9) Write a program to create a dataframe df1 containing sales of 8 months (row indexes) as :-
month1, month2, month3, month4, month5, month6, month7 and month8.
Add data of 4 salesmen as [‘Arjun’,’Rajan’,’Mahesh’,’Gautam’] as columns names
Display data of each salesman individually.
Find and display total sale of each salesman.
Display sale in 2nd, 3rd and 4th month of Rajan and Mahesh.
Increase sales in 3rd month of all salesmen by 10%.
Consider following data:
. Arjun Rajan Mahesh Gautam
month1 40000 51000 55000 42000
month2 80000 87000 57000 65000
month3 12000 52000 95000 52000
month4 52000 45000 23000 45000
month5 84000 62000 67000 65000
month6 45000 82000 66000 95000
month7 52000 54000 55000 223000
month8 32000 123000 85000 42000
#PROGRAM-9
sales={'Arjun':[40000,80000,12000,52000,84000,45000,52000,32000],
'Rajan':[51000,87000,52000,45000,62000,82000,54000,123000],
'Mahesh':[55000,57000,95000,23000,67000,66000,55000,85000],
'Gautam':[42000,65000,52000,45000,65000,95000,223000,42000]}
months=['month1','month2','month3','month4',
'month5','month6','month7','month8']
df1=pd.DataFrame(sales,index=months)
print(df1)
print('DISPLAYING EACH SALESMAN DATA....\n')
for (c1,c2)in df1.items():
print("\nCOLUMN INDEX",c1)
print("CONTAINS")
for i in c2:
print(i,end=',')
print("total sale of each salesman \n")
x=list(df1.columns)
for i in x:
print(i,sum(df1[i]))
#Display sale in 2nd, 3rd and 4th month of Rajan and Mahesh.
print("sale in 2nd, 3rd and 4th month of Rajan and Mahesh")
print(df1.loc['month2':'month4',['Rajan','Mahesh']])
#Increase sales in 3rd month of all salesmen by 10%.
df1.loc['month3',:]=df1.loc['month3',:]+1000
print(df1)
PrPROGRAM 10) Write a program to create a dataframe ENG containing Name, marks of Term-I ,Term-II,half yearly and annual in English. Rno is the index.
Example:-
name Term1 Term2 halfyearly annual
101 NISHA 75 65 72 78
121 TANYA 85 74 63 74
112 MAMTA 58 75 65 62
111 KIRAN 71 65 69 70
113 PREETI 63 66 55 76
123 NIMISHA 71 69 70 68
Also write codes to:-
Display name and marks in all exams of each student
Display highest and lowest marks in annual exam
Display average marks in halfyearly exam
Display term1 and annual marks of 121,111,113
Display term2 and annual marks of all students
ANSWER:
#PROGRAM-10
#creating dataframe
data={‘name’:[‘NISHA’,’TANYA’,’MAMTA’,’KIRAN’,’PREETI’,’NIMISHA’],
‘Term1’:[75,85,58,71,63,71],
‘Term2’:[65,74,75,65,66,69],
‘halfyearly’:[72,63,65,69,55,70],
‘annual’:[78,74,62,70,76,68]}
i=[101,121,112,111,113,123]
ENG=pd.DataFrame(data,index=i)
print(“DataFrame contains”)
print(ENG)
#Display name and marks in all exams of each student
for (r1,r2 )in ENG.iterrows():
print(“\nROW INDEX”,r1)
print(“CONTAINS”)
for val in r2:
print(val)
#Display highest and lowest marks in annual exam
print(“highest marks in annual exam”,ENG.annual.max())
print(“lowest marks in annual exam “,ENG.annual.min())
#Display average marks in halfyearly exam
print(“lowest marks in halfyearly exam “)
print(ENG.halfyearly.sum()/len(ENG.halfyearly))
#Display term1 and annual marks of 121,111,113
print(“term1 and annual marks of 121,111,113..”)
print(ENG.loc[[121,111,113],[‘Term1′,’annual’]])
#Display term2 and annual marks of all students
print(“term2 and annual marks of all students…”)
print(ENG.loc[:,[‘Term2′,’annual’]])ogram 10 Question)
Question-11:- Mr. Summit, a data analyst has designed the DataFrame df that contains data about Computer infrastructure with ‘S01’, ‘S02’, ‘S03’, ‘S04’, ‘S05’, ‘S06’ as indexes shown below.
| . | School | computers | non-working | working |
| S01 | MPS | 80 | 10 | 70 |
| S02 | SFC | 88 | 12 | 76 |
| S03 | JPS | 25 | 4 | 21 |
| S04 | APS | 45 | 6 | 39 |
| S05 | RLPS | 90 | 15 | 75 |
| S06 | DPS | 60 | 6 | 54 |
Write code for the following:-
i) Create the above dataframe
ii) display the data of working column of indexes S03 to S05.
iii) compute and display the difference of data of computers column and working column of the above given DataFrame.
iv) plot a line chart for computers and working columns of all school codes
v) display school name and working computers of S02, S03,S05,S06
ANSWER:
#QUESTION-11
import pandas as pd
import matplotlib.pyplot as plt
#i) Create the above dataframe
data={‘School’:[‘MPS’,’SFC’,’JPS’,’APS’,’RLPS’,’DPS’],
‘computers’:[80,88,25,45,90,60],
‘non-working’:[10,12,4,6,15,6],
‘working’:[70,76,21,39,75,54]}
i=[‘S01′,’S02′,’S03′,’S04′,’S05′,’S06’]
df=pd.DataFrame(data,index=i)
print(“DataFrame contains:”)
print(df)
#ii) display the data of working column of indexes S03 to S05.
print(“\nWorking column of indexes S03 to S05:”)
print(df.loc[‘S03′:’S05′,’working’])
#iii) compute and display the difference of data of computers column and working column of the above given DataFrame.
print(“\nDifference of computers and working column:”)
print(df[‘computers’]-df[‘working’])
#iv) plot a line chart for computers and working columns of all school codes
plt.plot(df.index,df[‘computers’],label=’Computers’,color=’blue’,marker=’o’)
plt.plot(df.index,df[‘working’],label=’Working’,color=’green’,marker=’s’)
plt.xlabel(‘School Code’)
plt.ylabel(‘Number of Computers’)
plt.title(‘Computer Infrastructure in Schools’)
plt.legend()
plt.show()
#v) display school name and working computers of S02, S03,S05,S06
print(“\nSchool name and working computers of S02, S03, S05, S06:”)
print(df.loc[[‘S02′,’S03′,’S05′,’S06’],[‘School’,’working’]])
PROGRAM 12) Given a dataframe PURCHASE as shown below:
| 2000 | 2010 | 2020 | |
|---|---|---|---|
| S1 | 520 | 450 | 290 |
| S2 | 240 | 520 | 240 |
| S3 | 360 | 755 | 115 |
| S4 | 400 | 300 | 120 |
| S5 | 600 | 350 | 310 |
| S5 | 870 | 450 | 350 |
Write code to create :
a) the above dataframe PURCHASE
b) add 5 in all the values of 2020 in dataframe
c) add a column average with average of the values of corresponding column values.
d) A bar chart to compare 2000 and 2010 columns of PURCHASE
e) A line chart from the 2010 and 2020 columns of PURCHASE
f) A bar chart to compare 2000 and 2020 columns
note:- use xlabel(), ylabel(), title(), colours, marker attributes, yticks()/yticks(), xlim()/ylim()
# program-12
import pandas as pd
import numpy as np
import matplotlib.pyplot as pl
d = {
2000: [520, 240, 360, 400, 600, 870],
2010: [450, 520, 755, 300, 350, 450],
2020: [290, 240, 115, 120, 310, 350],
}
dfr = pd.DataFrame(d, index=["s1", "s2", "s3", "s4", "s5", "s6"])
print(dfr)
print(dfr.loc["s1":"s6", 2020] + 5)
for i in range(0, 6):
a = sum(dfr.iloc[i, 0:3]) / 3
print(a)
s = np.arange(1, 7)
pl.bar(s, dfr[2000], color="blue", width=0.25)
pl.bar(s + 0.35, dfr[2010], color="pink", width=0.25)
pl.show()
pl.plot(dfr.index, dfr[2000])
pl.show()
pl.plot(dfr.index, dfr[2010])
pl.show()
pl.bar(s, dfr[2000], color="orange", width=0.25)
pl.bar(s + 0.35, dfr[2020], color="green", width=0.25)
pl.show()
PROGRAM-13:- Consider the following data of a medical store and plot the data on the line chart:
| Masks | Sanitizer | Hand wash | |
|---|---|---|---|
| March | 1500 | 4400 | 6500 |
| April | 3500 | 4500 | 5000 |
| May | 6500 | 5500 | 5800 |
| June | 6700 | 6000 | 6300 |
| July | 6000 | 5600 | 6200 |
| August | 6800 | 6300 | 4500 |

Answer-13
import matplotlib.pyplot as pp
mon = [‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’]
mask = [1500, 3500, 6500, 6700, 6000, 6800]
san = [4400, 4500, 5500, 6000, 5600, 6300]
hw = [6500, 5000, 5800, 6300, 6200, 4500]
pp.plot(mon, mask, label=’Mask’, color=’g’, linestyle=’dashed’, linewidth=4,
marker=’o’, markerfacecolor=’k’, markeredgecolor=’r’ )
pp.plot( mon, san, label=’Sanitizer’, color=’b’, linestyle=’dashed’, linewidth=4,
marker=’3′, markerfacecolor=’k’, markeredgecolor=’g’ )
pp.plot( mon, hw, label=’Handwash’, color=’r’, linestyle=’dashed’, linewidth=4,
marker=’v’, markerfacecolor=’k’, markeredgecolor=’b’ )
pp.title(“Fitwell Medical Store”)
pp.xlabel(“Months”)
pp.ylabel(“Covid Protections”)
pp.legend()
pp.show()
Q14: Write code to create and display a DataFrame df containing employee details. Also write statements to:
- Display the names of all employees.
- Display the name and position of managers.
- Display the names and cities of employees whose age is more than 30 and less than or equal to 35.
- Display the names of female employees.
- Display records for employees who do not live in Kanpur.
- Display the name, position, and city of female employees who live in Kanpur.
- Change the column name
PositiontoDesignation. - Add the employee Ayushman with details
[964, Programmer, Delhi, 28, M].
Empid Position City Age gender
Aakash 123 Manager Delhi 35 M
Sunakshi 251 Programmer Mumbai 37 F
Amitabh 236 Manager Kanpur 33 M
Madhuri 241 Programmer Mumbai 40 F
Ashish 258 Manager Kanpur 27 M
Akshay 269 Programmer Kanpur 34 M
Preeti 526 Programmer Delhi 26 F
Govinda 562 Manager Delhi 30 M
Rani 642 Manager Mumbai 28 F
Shilpa 576 Manager Kanpur 26 F
Ayushman 964 Programmer Delhi 28 M
ANS 14:-
import pandas as pd
Name = [
'Aakash', 'Sunakshi', 'Amitabh', 'Madhuri', 'Ashish',
'Akshay', 'Preeti', 'Govinda', 'Rani', 'Shilpa'
]
emp = {
'Empid': [123, 251, 236, 241, 258, 269, 526, 562, 642, 576],
'Position': [
'Manager', 'Programmer', 'Manager', 'Programmer', 'Manager',
'Programmer', 'Programmer', 'Manager', 'Manager', 'Manager'
],
'City': [
'Delhi', 'Mumbai', 'Kanpur', 'Mumbai', 'Kanpur',
'Kanpur', 'Delhi', 'Delhi', 'Mumbai', 'Kanpur'
],
'Age': [35, 37, 33, 40, 27, 34, 26, 30, 28, 26],
'gender': ['M', 'F', 'M', 'F', 'M', 'M', 'F', 'M', 'F', 'F']
}
df = pd.DataFrame(emp, index=Name)
print(df)
# Display names of all employees
print("\nNames of all employees:")
print(list(df.index))
# Display name and position of managers
print("\nName and position of managers:")
print(df[df['Position'] == 'Manager'][['Position']])
# Display names and cities of employees older than 30 and 35 or younger
print("\nEmployees aged over 30 and up to 35:")
print(df.loc[(df['Age'] > 30) & (df['Age'] <= 35), ['City', 'Age']])
# Display names of female employees
print("\nNames of female employees:")
print(list(df[df['gender'] == 'F'].index))
# Display records of employees who do not live in Kanpur
print("\nEmployees who do not live in Kanpur:")
print(df[df['City'] != 'Kanpur'])
# Display position and city of female employees living in Kanpur
print("\nFemale employees living in Kanpur:")
print(df.loc[(df['City'] == 'Kanpur') & (df['gender'] == 'F'), ['Position', 'City']])
# Change the column name Position to Designation
df.rename(columns={'Position': 'Designation'}, inplace=True)
print("\nDataFrame after renaming Position to Designation:")
print(df)
# Add Ayushman to the DataFrame
df.loc['Ayushman'] = [964, 'Programmer', 'Delhi', 28, 'M']
print("\nDataFrame after adding Ayushman:")
print(df)
PROGRAM 15): Write the code in pandas to create the following dataframes :
NAMAN AMAN
SEM1 SEM2 SEM1 SEM2
a 10 50 a 20 25
b 30 20 b 15 30
c 40 45 c 20 30
d 40 70 d 50 30
e 20 80 e 45 55
Write the commands to do the following operations on the dataframes given above :
(i) Create the two dataframes
(ii) To print total marks of both the students.
(iii) To print the different of marks of both students of corresponding semesters.
(iv) To rename column SEM1 as SEMESTER1 & SEM2 as SEMESTER2 in both the dataframes
(v) To change index labels to sub1,sub2,sub3,sub4, sub5
vi)plot bar chart for the semester1 marks of both students
#PROGRAM-15
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
d1={'SEM1':{'a':10,'b':30,'c':40,'d':40,'e':20},'SEM2':{'a':50,'b':20,'c':45,'d':70,'e':80}}
d2={'SEM1':{'a':20,'b':15,'c':20,'d':50,'e':45},'SEM2':{'a':25,'b':30,'c':30,'d':30,'e':55}}
#(i) Create the two dataframes
NAMAN=pd.DataFrame(d1)
AMAN=pd.DataFrame(d1)
print(NAMAN)
print(AMAN)
##(ii) To print total marks of both the students.
NAMAN['TOTAL']=NAMAN['SEM1']+NAMAN['SEM2']
AMAN['TOTAL']=AMAN['SEM1']+AMAN['SEM2']
print(NAMAN)
print(AMAN)
##(iii) To print the different of marks of both students of corresponding semesters.
print("DIFFERENCE OF MARKS OF NAMAN.....\n",NAMAN['SEM2']-NAMAN['SEM1'])
print("\n DIFFERENCE OF MARKS OF AMAN.....\n",AMAN['SEM2']-AMAN['SEM1'])
##(iv) To rename column SEM1 as SEMESTER1 & SEM2 as SEMESTER2 in both the dataframes
NAMAN.rename(columns={'SEM1':'SEMESTER1','SEM2':'SEMESTER2'},inplace=True)
AMAN.rename(columns={'SEM1':'SEMESTER1','SEM2':'SEMESTER2'},inplace=True)
print(NAMAN)
print(AMAN)
##(v) To change index labels to sub1,sub2,sub3,sub4, sub5
NAMAN.index=['sub1','sub2','sub3','sub4', 'sub5']
AMAN.index=['sub1','sub2','sub3','sub4', 'sub5']
print(NAMAN)
print(AMAN)
##vi)plot bar chart for the semester1 marks of both students
x=NAMAN.index
y1=list(NAMAN['SEMESTER1'])
y2=AMAN.SEMESTER1
n=np.arange(5)
plt.bar(x,y1,color='blue',width=0.3)
plt.bar(n+0.3,y2,color='red',width=0.3)
plt.show()
PROGRAM 16
Consider the details i.e. meters, speed, weight of different treadmills.
meters speed weight
Manual 122 10 20
Motorized 150 15 30
Inclined 100 20 15
Folding 230 18 85
Commercial 300 19 102
[a]Create a dataframe from the data
[b] display meters and speed of first and last treadmills
[c] change the weights of all machines to 25,38,23,89,112 respectively
[b] create bar chart from speed and meters columns of dataframe
[c] create bar chart from meters and weight columns of dataframe
[d] create scatter charts from speed and meters columns of dataframe
[e] create scatter charts from meters and weight columns of dataframe
##PROGRAM 16
import matplotlib.pyplot as plt
import numpy as np
##[a]Create a dataframe from the data
d={'meters':[122,150,100,230,300],
'speed':[10,15,20,18,19],
'weight':[20,30,15,85,102]}
dataf1=pd.DataFrame(d,index=['Manual','Motorized','Inclined'
,'Folding','Commercial'])
print(dataf1)
##[b] display meters and speed of first and last treadmills
print(dataf1.loc[['Manual','Commercial'],['meters','speed']])
##[c] change the weights of all machines to 25,38,23,89,112 respectively
print("\n CHANGING WEIGHTS..\n")
dataf1['weight']=[25,38,23,89,112]
print(dataf1)
##[b] create bar chart from speed and meters columns of dataframe
x=np.arange(5)
plt.bar(dataf1.index,dataf1['speed'],color="red",width=0.3,label='speed')
plt.bar(x+0.3,dataf1['meters'],color="green",width=0.3,label='meters')
plt.xlabel("names of treadmills")
plt.ylabel("speed and meters")
plt.legend()
plt.show()
##[c] create bar chart from meters and weight columns of dataframe
x=np.arange(5)
plt.bar(dataf1.index,dataf1['weight'],color="red",width=0.3,label='weight')
plt.bar(x+0.3,dataf1['meters'],color="green",width=0.3,label='meters')
plt.xlabel("names of treadmills")
plt.ylabel("weight and meters")
plt.legend()
plt.show()
##[d] create scatter charts from speed and meters columns of dataframe
plt.scatter(dataf1.index,dataf1['meters'],color="red",label='meters')
plt.scatter(dataf1.index,dataf1['speed'],color="green",label='speed')
plt.xlabel("names of treadmills")
plt.ylabel("speed and meters")
plt.legend()
plt.show()
##[e] create scatter charts from meters and weight columns of dataframe
plt.scatter(dataf1.index,dataf1['meters'],color="red",label='meters')
plt.scatter(dataf1.index,dataf1['weight'],color="green",label='weight')
plt.xlabel("names of treadmills")
plt.ylabel("weight and meters")
plt.legend()
plt.show()
PROGRAM 17) Given below is the score of 3 teams in 5 IPL matches.
. Match1 Match2 Match3 Match4 Match5
TeamA 200 307 240 153 150
TeamB 182 147 210 142 233
TeamC 350 222 371 195 240
TeamD 125 300 145 230 300
TeamE 215 275 255 240 260
Write a program to create a dataframe from the above data
Plot a bar chart using different colours, legend, title.
Save the contents of the dataframe to a csv file named ‘scores.csv’
Read the contents of csv file scores.csv and display details of Match1 and Match3
ANSWER:
#PROGRAM=17
import pandas as pd
import matplotlib.pyplot as p1
#Write a program to create a dataframe from the above data
score={'Match1':[200,182,350,125,215],
'Match2':[307,147,322,300,275],
'Match3':[240,210,371,145,255],
'Match4':[153,142,195,230,240],
'Match5':[150,233,240,300,260]}
dfscore=pd.DataFrame(score,index=['TeamA','TeamB','TeamC','TeamD','TeamE'])
print(dfscore)
#saving data to a csv file
dfscore.to_csv('scores.csv')
#plotting bar chart
dfscore.plot(kind='bar')
p1.xlabel('TEAMS')
p1.ylabel('SCORES OF 5 MATCHES')
p1.show()
##Read the contents of scores.csv and display details of Match1 and Match3
df1=pd.read_csv("scores.csv")
print("Printing details of Match1 and Match3..")
print(df1.loc[:,['Match1','Match3']])
PROGRAM 18) Navya has started an online business of stationery items. A list stores the number of orders in year 2021 ,2022 and 2023 are as follows:-
Year2021->.
Year 2022->.
Year 2023->.
Write a program to:-
[a] create dataframe for the above data
[b]to display orders in first three months in year 2022,2023
[c] plot this data on a horizontal bar chart for year 2022.
[d] plot line chart for years 2021 and 2022 to compare sales.Use different colours and also label the x-axis and y-axis.
[e] Write the data in a csv file order.csv
ANSWER:
#PROGRAM-18
import matplotlib.pyplot as plt
d={'Year2021':[500,250,235,432,320,540,230,350,380,450,260,750],
'Year2022':[450,256,740,120,410,510,218,413,850,890,450,560],
'Year2023':[250,546,340,720,450,520,290,480,250,800,400,600]}
month=['jan','feb','mar','apr','may','june','july','aug','sep','oct','nov','dec']
dfs=pd.DataFrame(d,index=month)
print(dfs)
##[b]to display orders in first three months in year 2022,2023
print("orders in first three months in year 2022,2023")
print(dfs.loc['jan':'mar',['Year2022','Year2023']])
##[c] plot this data on a horizontal bar chart for year 2022.
x=month
y=dfs['Year2022']
plt.barh(x,y,color=['r','b','g','y','c','m','r','b','g','y','c','m'])
plt.show()
##[d] plot line chart for years 2021 and 2022 to compare sales.
x=month
y1=dfs['Year2021']
y2=dfs['Year2022']
plt.plot(x,y1,color="red",label='Year2021',marker="*")
plt.plot(x,y2,color="blue",label='Year2022',marker="s")
plt.legend()
plt.show()
##[e] Write the data in a csv file order.csv
dfs.to_csv("order.csv")
PROGRAM 18) Navya has started an online business of stationery items. A list stores the number of orders in year 2021 ,2022 and 2023 are as follows:-
Year2021->[500,250,235,432,320,540,230,350,380,450,260,750]
Year 2022->[450,256,740,120,410,510,218,413,850,890,450,560]
Year 2023->[250,546,340,720,450,520,290,480,250,800,400,600]
Write a program to:-
[a] create dataframe for the above data
[b]to display orders in first three months in year 2022,2023
[c] plot this data on a horizontal bar chart for year 2022.
[d] plot line chart for years 2021 and 2022 to compare sales.Use different colours and also label the x-axis and y-axis.
[e] Write the data in a csv file order.csv
ANSWER:
#PROGRAM-18
import matplotlib.pyplot as plt
d={'Year2021':[500,250,235,432,320,540,230,350,380,450,260,750],
'Year2022':[450,256,740,120,410,510,218,413,850,890,450,560],
'Year2023':[250,546,340,720,450,520,290,480,250,800,400,600]}
month=['jan','feb','mar','apr','may','june','july','aug','sep','oct','nov','dec']
dfs=pd.DataFrame(d,index=month)
print(dfs)
##[b]to display orders in first three months in year 2022,2023
print("orders in first three months in year 2022,2023")
print(dfs.loc['jan':'mar',['Year2022','Year2023']])
##[c] plot this data on a horizontal bar chart for year 2022.
x=month
y=dfs['Year2022']
plt.barh(x,y,color=['r','b','g','y','c','m','r','b','g','y','c','m'])
plt.show()
##[d] plot line chart for years 2021 and 2022 to compare sales.
x=month
y1=dfs['Year2021']
y2=dfs['Year2022']
plt.plot(x,y1,color="red",label='Year2021',marker="*")
plt.plot(x,y2,color="blue",label='Year2022',marker="s")
plt.legend()
plt.show()
##[e] Write the data in a csv file order.csv
dfs.to_csv("order.csv")
PROGRAM-19
Consider the pandas dataframe “DF” given below:
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
Science 91 81 91 71 95
English 85 86 83 80 90
Hindi 97 96 88 67 99
Write the output of :
a. print(DF.loc[“Maths”] > 90)
b. print(DF.loc[:, “Arnab”] > 90)
c. print(DF.loc[‘Maths’: ‘Science’])
d. print(DF.loc[[‘Maths’,’English’],[‘Arnab’,’Riya’,’Mallika’]])
e. print(DF.loc[DF.loc[:, “Arnab”] > 90])
ANSWER-19-
ans[a]
Arnab False
Ramit True
Samridhi False
Riya False
Mallika True
Name: Maths, dtype: bool
Ans[b]
Maths False
Science True
English False
Hindi True
Name: Arnab, dtype: bool
Ans[c]
Arnab Ramit Samridhi Riya Mallika
Maths 90 92 89 81 94
Science 91 81 91 71 95
Ans[d]
Arnab Riya Mallika
Maths 90 81 94
English 85 80 90
Ans[e]
Arnab Ramit Samridhi Riya Mallika
Science 91 81 91 71 95
Hindi 97 96 88 67 99
PROGRAM 20) Consider the table given below:
Country Gold Silver Bronze Total
Australia 80 59 59 198
England 45 45 46 136
India 26 30 20 76
Canada 15 20 27 62
Now write a program to plot a bar chart from the medals won by the four countries.
Make sure that bars are separately visible and should be in different colours.
Also use suitable title, labels for x-axis and yaxis. Save the contents of the dataframe to a csv file named ‘countries.csv’
ANSWER-20:
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(10,7))
medals=('Gold','Silver','Bronze','Total')
Australia=[80, 59, 59, 198]
England=[45, 45, 46, 136]
India=[26, 30, 20, 76]
Canada =[15, 20, 27, 62]
x=np.arange(len(medals))
plt.bar(medals, Australia,width=0.15)
plt.bar(x+0.15,England,width=0.15)
plt.bar(x+0.30,India,width=0.15)
plt.bar(x+0.45,Canada,width=0.15)
plt.legend()
plt.xlabel("Medal type")
plt.ylabel("Tally of four countries")
plt.show()
SQL QUERIES-I
SQL QUERIES (STUDENT TABLE)
CONSIDER THE TABLE STUDENT AND WRITE THE SQL QUERIES FOR THE FOLLOWING:-
| SRNO | RNO | NAME | FNAME | CLASS | FEES | DOB |
|---|---|---|---|---|---|---|
| 21312 | 21 | ANANYA | MOHIT | IX-A | 2500 | 2004-1-1 |
| 12541 | 12 | NISHA | ARUN | IX-B | 2600 | 2004-02-02 |
| 14581 | 14 | NAVISHA | GAGAN | X-A | 3500 | 2003-01-01 |
| 14785 | 5 | ARUNA | INDER | X-B | 3600 | 2002-04-04 |
| 21451 | 6 | ANVITA | PANKAJ | XI-A | 4500 | 2001-02-22 |
| 21552 | 23 | TEENA | ROHIT | XII-A | 5000 | 2002-05-12 |
| 19635 | 41 | DIVYA | ARJUN | XI-B | 4600 | 2001-06-13 |
| 14578 | 14 | VARNITA | AMAN | X-B | 3600 | 2003-10-23 |
| 19852 | 12 | UDISHA | NISHANT | XI-A | 4500 | 2001-12-25 |
| 14852 | 52 | ISIKA | MOHAN | XII-A | 5000 | 2001-11-24 |
| 19635 | 6 | PRERNA | YOGESH | XI-B | 4600 | 2002-11-18 |
Q.1. DISPLAY NAME AND ROLLNO. OF THE STUDENTS OF CLASS X-A.
ANS:- SELECT NAME,RNO
FROM STUDENT
WHERE CLASS='X-A';
Q.2. DISPLAY NAME AND FEES OF THE STUDENTS WHOSE ROLL NUMBER IS BELOW 10.
ANS:- SELECT NAME,FEES
FROM STUDENT
WHERE RNO<10;
Questions 3–6 (Eighth Image):
Q.3. DISPLAY NAME, ROLLNO AND CLASS OF THE STUDENTS WHOSE FEES IN THE RANGE OF 2000 AND 3000.
SELECT NAME,RNO,CLASS FROM STUDENT
WHERE FEES>=2000 AND FEES<=3000;
OR
SELECT NAME,RNO,CLASS FROM STUDENT
WHERE FEES BETWEEN 2000 AND 3000;
Q.4. DISPLAY ALL THE DETAILS OF THE STUDENTS OF CLASS XI.
ANS:- SELECT * FROM STUDENT WHERE CLASS='XI-A' OR CLASS='XI-B';
OR
SELECT * FROM STUDENT WHERE CLASS LIKE 'XI-%';
Q.5. DISPLAY ALL THE DETAILS OF THE STUDENTS OF CLASS XI AND XII.
ANS:- SELECT * FROM STUDENT
WHERE CLASS IN('XI-A','XI-B','XII-A','XII-B');
Q.6. DISPLAY SRNO, NAME OF THE STUDENTS WHOSE FATHER’S NAME END WITH ‘A’
SELECT SRNO,NAME FROM STUDENT WHERE FNAME LIKE '%a';
Q.7. DISPLAY ROLLNO, NAME, FEES OF THE STUDENTS WHOSE NAME BEGIN WITH S OR N.
SELECT RNO,NAME,FEES
FROM STUDENT
WHERE NAME LIKE 'S%' OR NAME LIKE 'N%';
Q.8. DISPLAY THE DETAILS OF THE STUDENTS IN ASCENDING ORDER OF SRNO.
SELECT *
FROM STUDENT
ORDER BY SRNO ASC;
Q.9. DISPLAY THE DETAILS OF THE STUDENTS BORN IN YEAR 2001.
SELECT *
FROM STUDENT
WHERE YEAR(DOB)=2001;
Q.10:- DISPLAY NAME, FATHER’S NAME AND FEES OF THE STUDENTS IN DESCENDING ORDER OF FEES.
SELECT NAME,FNAME,FEES
FROM STUDENT
ORDER BY FEES DESC;
Q.11. DISPLAY TOTAL NO. OF STUDENTS WHOSE FEE IS ABOVE 3000
SELECT COUNT(*)
FROM STUDENT
WHERE FEE>3000;
Q.12. DISPLAY TOTAL NO OF STUDENTS IN EACH CLASS
SELECT CLASS,COUNT(*)
FROM STUDENT
GROUP BY CLASS;
Q.13. DISPLAY HIGHEST AND LOWEST FEES OF THE STUDENTS
SELECT MAX(FEES),MIN(FEES)
FROM STUDENT;
Q.14. DISPLAY DETAILS OF STUDENTS BORN IN MAY.
SELECT *
FROM STUDENT
WHERE MONTH(DOB)=5;
Q.15. DISPLAY FATHER’S NAME AND PHONE NO. OF CLASS XII STUDENTS
SELECT FNAME,PHNO
FROM STUDENT
WHERE CLASS LIKE 'XII%';
SQL QUERIES -II
Consider the tables PRODUCT and BRAND given below:
Table: PRODUCT
| PCode | PName | UPrice | Rating | BID |
|---|---|---|---|---|
| P01 | Shampoo | 120 | 6 | M03 |
| P02 | Toothpaste | 54 | 8 | M02 |
| P03 | Soap | 25 | 7 | M03 |
| P04 | Toothpaste | 65 | 4 | M04 |
| P05 | Soap | 38 | 5 | M05 |
| P06 | Shampoo | 245 | 6 | M05 |
Table: BRAND
| BID | BName | Distributor |
|---|---|---|
| M02 | Dant Kanti | ABC |
| M03 | Medimix | XYZ |
| M04 | Pepsodent | ABC |
| M05 | Dove | XYZ |
| M06 | Sunsilk | ABC |
Write SQL queries for the following:
(i) Display product name and brand name from the tables PRODUCT and BRAND of all products whose price is above 100
(ii) Display name and rating of those products whose product name begins with ‘S’ in descending order of Unit price.
(iii) Display the total and average rating of Medimix and Dove brands
(iv) Display the name, price, and rating of those products whose brandname contains more than 7 characters
(v) display total no. of shampoos in the table
(Vi) display total no. of distributors
(vii)display product code, productname, distributor name from tables whose rating is more than 5
(viii) display pcode, pname, bname and rating of products with unit price less than 100
(ix) add a product details in the table product (P07,Soap,45,5,M06)
(x) display code and name of product and brand name and distributor of all toothpaste.
ANSWERS:-
i)SELECT PNAME,BNAME FROM PRODUCT P, BRAND B
WHERE P.BID=B.BID AND UPRICE>100;
ii)SELECT PNAME, RATING FROM PRODUCT WHERE PNAME LIKE ’S%’ ORDER BY UPRICE DESC;
iii)SELECT SUM(RATING),AVG(RATING) FROM PRODUCT P, BRAND B WHERE BNAME IN (‘MEDIMIX’,’DOVE’) AND WHERE P.BID=B.BID;
iv) SELECT PNAME, UPRICE, RATING FROM PRODUCT P,BRAND B WHERE LENGTH(BNAME)>7 AND P.BID=B.BID;
(v) SELECT COUNT(*) FROM PRODUCT WHERE PNAME=’SHAMPOO’;
(Vi) SELECT COUNT(DISTINCT DISTRIBUTOR) FROM BRAND;
(vii)SELECT PCODE, PNAME, DISTRIBUTOR FROM PRODUCT,BRAND WHERE PRODUCT.BID=BRAND,BID AND RATING>5;
(viii) SELECT PCODE, PNAME, BNAME, RATING FROM PRODUCT,BRAND WHERE PRODUCT.BID=BRAND,BID) AND UPRICE<100;
(ix) INSERT INTO product VALUES (‘P07’,’Soap’,45,5,’M06’)
(x) SELECT PCODE, PNAME,BNAME, DISTRIBUTOR FROM PRODUCT,BRAND WHERE PRODUCT.BID=BRAND,BID AND PNAME=’TOOTHPASTE’;
S. No. Date Program / Topic
1 01.05.26 Program-1 - Create a Series Object
2 05.05.26 Program-2 - Create a Series of Marks
3 11.05.26 Program-3 - Create Series staff and salaries
4 15.05.26 Program-4 - Create a series Total
5 06.07.26 Program 5 - Create Dataframe Sales
6 11.07.26 Program 6 - Create Dataframe of Salary
7 15.07.26 Program 7 - Create Dataframe Student
8 20.7.26 Program 8 - Create dataframe item
9 27.07.26 Program 9 - Create dataframe df1
10 31.07.26 Program 10 - Create dataframe ENG
11 07.08.26 Program 11 - Create dataframe of Data Infrastructure
12 12.08.26 Program-12 - Create dataframe Purchase
13 17.08.26 Program 13 - Plot a graph of Medical store
14 22.08.26 Program 14 - Create dataframe employee
15 26.08.26 Program 15 - Create two dataframes
16 21.09.26 Program 16 - Create dataframe treadmills
17 26.09.26 Program 17 - Create dataframe of 3 teams in IPL
18 29.09.26 Program 18 - Create dataframe of orders in years
19 18.10.26 Program 19 - Create dataframe DF
20 20.10.26 Program 20 - Plot bar chart of different Medals
21 24.10.26 SQL Queries-1
22 30.10.26 SQL Queries-2
