Class 12 Informatics Practices
Practical File Questions, Code & Outputs
Academic Year: 2025 26
Generated on: 24 Aug 2025, 09:15:32
All charts are plotted with Matplotlib.
Q1: Series from Dict and ndarray
Question:
iCmrepoartet ap apnadnads a as sS ep rdi e s from (i) a dictionary of values and (ii) a NumPy
ndarray.
import numpy as np
Coxsi=Spe[_sed ddf'r.ae,tariS'_oxee
'(w
m _iedfsir(coatmrr=d,icptdi:.nSder
d'i:,ct'sr
)y', 'z']) data_d i ct = {'a':
a 10
10, 'b': 20, 'c': 30}
abprrint=(20"nSpe.ra 1d5i,ct:2"5), 35])
irersay(f[r5o,m
scp_rfirnot(m3s_0n_d
fro=m_dict)
dp tr yi pn et :("\in St e6 r4 ies from ndarray:")
print(s_from_nd)
Series from ndarray:
w 255
Output:
x
z 15
35
ydtype: int64
Q2: Series from List
Question:
Create a pandas Series using a Python list.
values = [100, 200, 300, 400]
Coladbeel:s = ['p', 'q', 'r', 's']
psind=exp=d1l.0aS0beerlise)s(valu
es, qprint(2s0)0
r 300
s 400
Oduttyppeu:t:int64
Q3: Empty, Scalar & Array Series
Question:
Create (i) an empty Series, (ii) a scalar Series, and (iii) a Series from a NumPy array.
e _s = p d .Se r i e s ( d t y p e= ' f l o a t6f4l'o)at64)
E mpty Ser ie s : S e r i e s ( [ ] , d t y p e :
Code:
scpadl.aSre_rsies=(nppd.aSrearnigees(47),,inidnedxe=x
print("\nScalar Series:")
[='lAi's,t('WBX'Y,Z')C)'])
nSppcr_aislnat(r="scESamelpratirye_ss:S)eries:",
empty_s) ASperriinet(s7"\
fnrSoemriNeusmPyfroamrraNyu:mPy array:")
BWprint(70np_s)
C X 71
Ydtype:2 int64
Output:
Z 3
dtype: int64
Q4: GroupBy on Quarterly Sales
Question:
Create a DataFrame of quarterly sales with columns: category, item, expenditure. Group by category
and print total expenditure per category.
Cosadl = pd.DataFrame({
ees:
'Electronics'], 'expe'nicdtaeittme'ug:roer'y:':
[1[2'0FA0op,opdl'e8,s0'0,'Fo3'o0Bd0r',e,ad7'0',0S,ta'tP1ie5on0ns0e']r,y',Not'eSbtoaotkiso'n,ery
''M,ouse'],
}a)s_index=False)['expenditure'].sum()
tportianlts(sa=lessa)les.groupby('category',
cpartiengto(r"y\:n"T)otal expenditure per
print(totals)
c a t e g7 o0 r0 y item expenditure
O0utput Food Apples 1200
: B r e a d
4 Elec t r o n ics M o u s0 e
8 0 1500
12 S t aytio Pens 300
oroydo rexpenditure
nFecateg
30TotaElSetcaetxripoeniedcrisytureNotpebroocka1st5e0g0ory:
1 Food 2000
2 Statio1n0e0r0y
Q5: DataFrame Labels, Dtypes, Dimensions
Question:
Create an examination result DataFrame and display row labels, column labels, dtypes of each column,
and the dimensions.
e'xCode
XaImI-A:=',pd.'DXaItIa-FB r' a] m, e({
' Name': ['Asha', 'Vikram', 'Neel'],
103])'Math': [92, 78, 85],
print
abels:", ' (Class':
eS'x :['XII-A
am) [88,' , 91, 73]
exam.columns.tolist())
}p,rinitn(d"e\ (index):", exam.index.tolist())
xn=DR[to1yw0p1,elsa:
b1"e0)l2s,
print("eCxoalmu.md
ntypes)
'Math', 'CS']
print("\nDimensions:", exam.shape)
Dtypes:
1 0 Name Class Math CS
e N
a 1 XI AIsh- 73 92 88
eml
e 5ABbjecXtII8-
o a
O1u0t2puVti:kram XII-A 78 91
Class object
1 RM 0oa 3wth labels in( ti 6n 4dex): [101, 102, 103]
object
CSolumn labeiln st:64['Name', 'Class',
dDtiympeen :sions: (3, 4)
Q6: Remove Duplicates
QOureigsitniaoln: :
FilteAr ouBt rows based on duplicate records in a DataFrame.
0d f =1 pd1.0DataFrame({'A': [1,2,2,3], 'B':[10,20,20,30]})
1prin2t("2O0riginal:")
Co2prdien2t:(d2f0)
3prin3 t("3 \0 nWithout duplicates:")
print(df.drop_duplicates()) Without
duplicates:
A B
O0utp 1 ut1:0
2 20
13 3 30
Q7: CSV Import/Export
Question:
Importing and exporting data between pandas and a CSV file.
Cos' a/dmepn lt:e/da= tap /d s. aD ma pt la eF .r ca sm ve '({'id':[1,2,3],
'name':
['Ana','Ben','Cid']})
Scpsasravime_npdptla(et".thStoao:v_=ec/dsmvn(tc/osd:va"_t,paa/ctshav,m_plai
etn.hdc)esxv=False)
Llporaidnetd("L=boaacpdkde:.dreabda_ccks:v"()csv_path)
prinitd(lnoaamdeed)
0 1 Ana
1 2 Ben
O2utp3ut:Cid
Q8: Compute Grades
Q6u6e,s8t5i]on:
I}t)erate over a DataFrame (names, marks), compute grades, and add a 'Grade' column.
d>m'Name':
Code:e afrk7['Asha','Vikram','Neel','Riya'],
s0g:ra=drept(dum.r)Dn:ata'FBr'ame({
if= m >= 960: return ' CA '+ '
ir'feMtaurmrkns>'=:'D8'0[:9
2,ret7u8r,n 'A' if m
marks['GMraardkes'].a=pply(g
rade)
print(Nmaamreks)Marks
Grade
0 Asha 92 A+
1 Vikram 78 B
O 2u t p uNte:e l 66 C
3 Riya 85 A
Q9: School Result Analysis
Question:
Given school result data, analyze performance on different parameters (subject-wise and class-wise).
[9d2
Coresul e,7:8,85,71,88,69],
'tCsS':= pd.[D8a8t,a9F1r,a7m3e,(8{2,95,77],
'ENCnalgma'es:'s:':[8'[5A',sX8hI0aI,'-
7,A9',V,9i'0kX,rI7aI6m-,'A8,'8',]N'eXeIlI'-,B'R,i'yXaI'I,-'BI's,h'aXaInI'-,A'M,e'eXrIaI'-]B ,' ] ,
})Subj'eMcat-hw'i:se mean
#asvuebrjaegcet_mteoatnasl = results[['Math','CS','Eng']].mean()
results.groupby('Class')['Total'].mean()
#prresiCunlltat(srs[e-'swTuiolstesa)l'] = results[['Math','CS','Eng']].sum(axis=1)
cplraisnst_(sa"uv\bgnjSeu=cbtj_emceta-nwsi)se means:")
print("\nClass-wise average total:") print(class_avg)
wise means:
Name Class Math CS Eng Total
O04Math2
utput: 80.500000
Aa
C Is
s 78
43 a n9 0
S hah XII
A-
8 24
98 89 8756 2 65 59
1 2 85
9
average t8o4t. a3l3:33338
1 ViMk XII- 83 5 7898 2 3 74
25Eng
eN rearem A B 7 67 9
a l
Class 83.000000
3d t y p e: RiyfaloatX6I4I-B 71 82 90
XI I - A 257.666667
XSIuIb- 238.000000
jBect-
NCalmaes:s-wT io st eal, dtype: float64
Q9 Chart: Subject-wise Average Marks
84.5
Subject Mean
84.0
83.5
83.0
Average Marks
82.5
82.0
81.5
81.0
80.5
Math CS Eng
Subject
Q10: DataFrame & Chart with Legend
Question:
Create a DataFrame for analysis and plot a chart with title and legend.
sales_q = pd.DataFrame({
130, :180],
Code ' Quarter': ['Q1','Q2','Q3','Q4'],
'Cost': [80, 95, 90, 110]
}) 'Revenue': [120, 150,
print(sales_q)
Quarter Revenue Cost
O1 90 Q1 Q2 120
0utput:
150
80
95
2 Q 34 1 38 0 110
3
Q10 Chart: Revenue vs Cost
Revenue
180 Cost
160
140
Amount (in lakhs)
120
100
80
Q1 Q2 Q3 Q4
Quarter
Q11: Plant Growth Line Chart
Question:
Plot a simple line chart showing the growth of a plant over 5 days.
days = [1,2,3,4,5]
height_cm = [10, 12, 15, 18, 22]
Cofodred:, h in zip(days, height_cm):
pass # values shown in line chart
ODuattpa upto:ints (day, height_cm): [(1, 10), (2, 12), (3, 15), (4, 18), (5, 22)]
Q11 Chart: Plant Growth over 5 Days
Height (cm)
22
20
18
Height (cm)
16
14
12
10
1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0
Day
Q12: Marks Bar Chart
Question:
Create a bar chart showing marks obtained by a student in 5 subjects.
C os udb ej e: c t s
= ['Math','CS','Eng','Physics','Chem'] marks =
[92, 88, 85, 78, 81]
OSuutbpjeuctt:s & Marks: [('Math', 92), ('CS', 88), ('Eng', 85), ('Physics', 78), ('Chem', 81)]
Q12 Chart: Student Marks
100
92
88
85
81
80 78
60
Marks
40
20
0
Math CS Eng Physics Chem
Subject
Q13: Streams Horizontal Bar Chart
Question:
Plot a horizontal bar chart showing the number of students in different streams.
Costdreea:ms = ['Science','Commerce','Arts'] counts
= [45, 38, 32]
OSuttrpeaumts: & Counts: [('Science', 45), ('Commerce', 38), ('Arts', 32)]
Q13 Chart: Students per Stream
Arts 32
Stream
Commerce 38
Science 45
0 10 20 30 40
Number of Students
Q14: Time Spent Pie Chart
Question:
Draw a pie chart showing the percentage of time spent by a student on various activities in a day.
C oa cdt ei v: i t i e s = ['Study','Sleep','Leisure','Exercise','Other'] hours = [6, 8, 4,
1, 5] #
total 24 hours
Output:
Activities & Hours: [('Study', 6), ('Sleep', 8), ('Leisure', 4), ('Exercise', 1), ('Other', 5)]
Q14 Chart: Daily Time Distribution
Other
Study
20.8%
25.0%
Exercis
e
4.2%
16.7%
33.3%
Leisure
Sleep
Q15: City Population Bar Chart
Question:
Write a Python script to display a bar chart for population of five cities.
Cocidteie:s = ['Delhi','Mumbai','Kolkata','Chennai','Bengaluru'] population_lakhs = [198,
204,
148, 112, 125]
Output:
1C1i2t)i,es('&BePnogp 1( 2l 5a )k ]h s ) : [('Delhi', 198), ('Mumbai', 204), ('Kolkata', 148), ('Chennai',
auluartui'o,n
Q15 Chart: Population of Five Cities
204
200 198
175
150 148
125 125
Population (lakhs)
112
100
75
50
25
0
Delhi Mumbai Kolkata Chennai Bengaluru
City
Q16: Favourite Fruits Pie Chart
Question:
Display a pie chart showing favourite fruits of students with explode and shadow effects.
fruits = ['Apple','Banana','Mango','Orange']
Covodtees: = [25, 18, 32, 15]
explode = [0.05,
0.05, 0.1, 0.05] # highlight Mango
OFurtupitust:& Votes: [('Apple', 25), ('Banana', 18), ('Mango', 32), ('Orange', 15)]
Q16 Chart: Favourite Fruits
Orange
16.7%
Mango
35.6%
27.8%
Apple
20.0%
Banana
A:
[[1 2]
[3 4]]
Q17: Concatenate 2D Arrays
Question:
BP :rogram to concatenate two 2D arrays into a single array.
[[5 6]
A[7= 8n]p].array([[1,2],[3,4]])
Coprint("A:\n",
B d=en:p.array([[5,6],[7,8]])
A)
Cporni=cnatnt(pe".n\canotBne:cd\
ant"e(,nraotwBe-) (w (i As ,e ) :B ) , axis=0)
pr[ i[ n1 t(2 "] \nConcatenated (row-wise):\n", C)
[3 4]
[5 6]
Ou[t7p8u]t]:
Q18: Sorting a DataFrame
Question:
Sort the rows in a DataFrame by one or more columns.
'Marks':[92,78,66,85]
unsorted_df = pd.DataFrame({
Co})prdient':(N"aOmrei'g:i[n'aAls:h"a)','Vikram','Neel','Riya'],
print(unsorted_df)
Odprerisigcnietn(ad"li\:ngS:o"r)ted by Marks
print(NuanmseortMeadr_kdsf.sort_values(by='Marks',
ascending=False)) 0SortedAshb ay Marks92descending:
O12uVikt pNuraatmm e Mark7s8
N e:e l92
0 Asha
3 Riya 66
85
7 V i k r a m
N e e l 66
8
1
2
Q19: Write/Read stud.csv
Question:
Write to a CSV file 'stud.csv' and then display its contents.
stud = pd.DataFrame({
'Mark'sR'o:l[l9N2o,'7:8[,18,52],3],
Code:
}) 'Name':['Asha','Vikram','Neel'],
srteuad_pbatchk = 'p/dm.nrte/ada_tcas/vs(tsutdu.dc_spva'th)
psrtiundt.(t"oS_acvsevd(stuod:_"p,atsht,ud_ipnadtehx)=False)
print(read_back)
Saved to: /mnt/data/stud.csv
RollNo Name Marks
Output:
0 1 78Asha 92
Vikram
12 23 Neel 85
Q20: Binary Operations on DataFrames
Question:
df1:
PerfoArmBbinary operations (addition, subtraction) on two DataFrames with alignment.
Coxy 1de42 : 5
dzpfd1.D3a=ta6pFdr.aDmaet(a{F'rAa'm:e[(1{0',A2'0:,[310,]2,'3B]',:'[B4'0:,[540,,56,06]},
index=['xy','yz','zw'])
dpfr2int=("d\fn1d:f\2n:"\,n",df1d)f2)
pd( rff 2i n:l tl (_ "v \a nl Au de d=0)( :fill_value=0):\n", df1.add(df2, fill_value=0))
AAB B
ywprin13t0(."0\4n0S6u0b.t0ract (fill_value=0):\n", df1.sub(df2, fill_value=0))
zxSubt20r1a.c0t50(f4i.l0l_value=0):
wy 3102.0A6045.0B
Output:
zw -32 03 .0 -65 06 .0
xA 1.0 4.0
dd
y -8.0 -35.0
z -17.0 -44.0
Q21: Create 'student' Table
Question:
Create a student table with (student_id PRIMARY KEY, name, marks).
CREATE TABLE IF NOT EXISTS student (
Codes:tudent_id INTEGER PRIMARY KEY,
NOT NULL,
nmamreksTEIXNTEGER
)
Output:
(See chart on next page.)
Q22: Insert Records
Question:
Insert the details of a new student into the student table.
INSERT INTO student (student_id, name, marks) VALUES
(1, 'Asha', 92),
Co(2d,e':Vikram', 78),
(3, 'Neel', 85),
(4, 'Riya', 88)
SCEoLlEuCmTns:*
Fs Rt Ou Mdens t_u id de ,nt name, marks
(1, 'Asha', 92)
(2, 'Vikram', 78)
O(u3t,p'uNte:el', 85)
(84 'Riya',
8, )
Q23: Delete a Record
Question:
Delete the details of a student (student_id=2) from the table.
CoDEdLeET:E FROM student WHERE student_id
= 2 SCEoLlEuCmTns:*
Fs Rt Ou Mdens t_u id de ,nt name, marks
(1, 'Asha', 92)
(3, 'Neel', 85)
O(u4t,p'uRti:ya', 88)
Q24: SELECT with Condition
Question:
Use SELECT to get details of students with marks more than 80.
Code:
SCEoLlEuCmTns:*
FsRtOuMdenst_uidde,ntnaWmHeE,REmamrakrsk
s > 80 (1, 'Asha', 92)
(3, 'Neel', 85)
O(u4t,p'uRti:ya', 88)
Q25: Aggregate Functions on Marks
Question:
Find MIN, MAX, SUM, and AVG of marks in the student table.
SsEuLmE_CmTarkMsI,N(marks) AS min_marks,
Code: MAAVXG(marks) AS amvagx_marks,
FROM stuS dU eM n( tmarks) AS
Columns: min_marks, max_marks, sum_marks, avg_marks
O(u8t5p, u9t2:,265, 88.33333333333333)
Q26: GROUP BY Country
Question:
Find the total number of customers from each country using GROUP BY.
EA
Cc RustomerT _A nB aL mE e IFTEXN TO ,T EXISTS
Code:
TEcustomers (
couusnttormyer_TiEdXTINTEGER
PRIMARY KEY,
)
Ic No Su En Rt Tr y )I N TV OA L Uc Eu Ss t o m e r s (customer_id, customer_name, (1,'Anita','India'),
(2,'Brian','UK'),(3,'Cheng','China'),(4,'Deepa','India'), (5,'Esha','India'),(6,'Fiona','UK')
SELECT country, COUNT(*) AS total_customers FROM
Ccoulsutmonmse:rscoGuRnOtUrPy,BYto
ctoauln_tcruystomers ('China', 1)
('India', 3)
O(u'tUpK'u,t:2)
Q27: ORDER BY Marks DESC
Question:
Write a SQL query to order the (student_id, marks) table in descending order of marks.
Code:
SCEoLlEuCmTns:stusdteundte_nitd_,id,marmkasrksFROM student
ORDER BY marks DESC (1, 92)
(4, 88)
O(u3t,p8u5t):
Q28: SELECT * FROM student
Question:
Write SQL query to display all the records of the student table.
Code:
SCEoLlEuCmTns:*
Fs Rt Ou Mdens t_u id de ,nt name, marks
(1, 'Asha', 92)
(3, 'Neel', 85)
O(u4t,p'uRti:ya', 88)
Q29: String Functions
Question:
Demonstrate SQL string functions (UPPER, LOWER, LENGTH, SUBSTR).
Code:
SELECT name, UPPER(name) AS upper_name, LOWER(name) AS lower_name, LENGTH(name) AS
len_name, SUBSTR(name,1,2) AS first_two FROM student
Columns: name, upper_name, lower_name, len_name, first_two
Output:
('Asha', 'ASHA', 'asha', 4, 'As')
('Neel', 'NEEL', 'neel', 4, 'Ne')
('Riya', 'RIYA', 'riya', 4, 'Ri')
Q30: Date & Time Functions
Question:
Demonstrate SQL date and time functions.
Code:
SELECT DATE('now') AS today_date, TIME('now') AS current_time, DATETIME('now') AS
current_datetime
OCuotlpumunts:: today_date, current_time, current_datetime
0(9':21052:54-0 '8 )- 24', '09:15:40', '2025-08-24