CBSE::CLASS – XII
INFORMATICS PRACTICES
MATERIAL,
CBSE QUESTIONS, ANSWERS
COLLECTED MATERIAL FROM VARIOUS SOURCES
2025.26
PYTHON BOOK & MySQL – First 2 Chapters
1. SERIES 2. DATAFRAMES (PANDAS 1 & 2 )
3. CSV FILES 4. DATA VISUALISATION 5.MySQL
CONTENTS
Chap Chapter Name Page No.
No
1 Series – Material 1
2 Series – Old Questions 31
3 DataFrames – Material 51
4 DataFrames – Old Questions 81
5 CSV Files – Materil & Old Questions 113
6 Data Visualisation – Material 123
7 Data Visualisation – Old Questions 138
8 Worksheets 152
9 MySQL – Database Concepts 168
10 MySQL - Functions 199
Name of the Student : ______________________________
THIS MATERIAL IS ONLY FOR PREPARATION PURPOSE.
SHOULD NOT USE FOR COMMERCIAL PURPOSE
I HAVE COLLECTED THIS MATERIAL FROM VARIOUS
SOURCES. I HAVE BEEN PREPARING AND TEACHING
FROM A GREAT AUTHOR’S BOOK. THANKS TO THAT AUTHOR.
ALSO THANKS TO CBSE, FOR PROVIDING CBSE SAMPLE PAPERS AND BOARD
PAPERS ALONG WITH MARKING SCHEMES.
THIS MATERIAL ALONE WILL NOT BE SUFFICIENT.
PLEASE GO THROUGH TEXT BOOK ALSO.
Dear Student/Reader, I have collected/prepared this material with the good intention to
make the XIIth class Informatics Practices students to understand important models and to
score good marks. To score full marks, one must prepare all the syllabus prescribed by
CBSE.
As I have collected/prepared the above material, some through my own answers,
marking schemes from CBSE, copied material from various other sources, etc, there might
be some typing mistakes, or any other errors. So reader should read carefully.
**ALL THE BEST**
Your ‘s Ever…. Dear…. Faculty, Friend & Well Wisher: MRK
Email: ptl4blog@gmail.com
XII – IP –PYTHON - CONCEPT
Data Handling using Pandas and Data Visualization (25 Marks)
Introduction to Python libraries- Pandas, Matplotlib.
Data structures in Pandas - Series and Data Frames.
Series: Creation of Series from – ndarray, dictionary, scalar value; mathematical operations;
Head and Tail functions; Selection, Indexing and Slicing.
Data Frames: Creation - from dictionary of Series, list of dictionaries, Text/CSV files; display; iteration; Operations on rows and
columns: add, select, delete, rename; Head and Tail functions; Indexing using Labels, Boolean Indexing;
Importing/Exporting Data between CSV files and Data Frames.
Data Visualization: Purpose of plotting; drawing and saving following types of plots using Matplotlib – line plot, bar graph,
Histogram.
Customizing plots: adding label, title, and legend in plots.
PANDAS INTRODUCTION
Introduction to Python Libraries:
Python libraries contain a collection of built in modules that allow us to perform many actions without
writing detailed programs for it. Each library in Python contains a large number of modules that one can
import and use.
NumPy, Pandas and Matplotlib are three well-established Python libraries for scientific and analytical
use. These libraries allow us to manipulate, transform and visualise data easily and efficiently.
NumPy, which stands for ‘Numerical Python’, is a library. It is a package that can be used for
numerical data analysis and scientific computing. NumPy uses a multidimensional array object and has
functions and tools for working with these arrays. Elements of an array stay together in memory, hence, they
can be quickly accessed.
PANDAS (PANel DAta) is a high-level data manipulation tool used for analysing data. It is Python’s
library for data analysis. Pandas has derived its name from “panel data system”, which is an ecometrics
term for multi dimensional, structured data sets. Pandas has become a popular choice for data analysis.
It is very easy to import and export data using Pandas library which has a very rich set of functions. It
is built on packages like NumPy and Matplotlib and gives us a single, convenient place to do most of our data
analysis and visualisation work.
Pandas has three important data structures, namely – Series, DataFrame and Panel to make the
process of analysing data organised, effective and efficient.
Data analysis refers to process of evaluating big data sets using analytical and statistical tools so as
to discover useful information and conclusions to support business decision-making.
The main author of Pandas is Wes McKinney.
Note: Pandas uses NumPy as its support library and hence many datatypes, constants and functions of NumPy
are frequently used with Pandas.
The Matplotlib library in Python is used for plotting graphs and visualisation. Using Matplotlib, with
just a few lines of code we can generate publication quality plots, histograms, bar charts, scatterplots, etc. It
is also built on Numpy, and is designed to work well with Numpy and Pandas.
You may think what the need for Pandas is when NumPy can be used for data analysis.
Following are some of the differences between Pandas and Numpy:
1. A Numpy array requires homogeneous data, while a Pandas DataFrame can have different data types (float,
int, string, datetime, etc.).
2. Pandas have a simpler interface for operations like file loading, plotting, selection, joining, GROUP BY,
which come very handy in data-processing applications.
3. Pandas DataFrames (with column names) make it very easy to keep track of data.
4. Pandas is used when data is in Tabular Format, whereas Numpy is used for numeric array based
data manipulation.
Installing Pandas : pip install pandas (using Command line)
XII – IP (2025.2026 Material & Old CBSE Questions) 1 1. Series
Why Pandas? (Or) Benefits of Pandas :
❖ Pandas is an open source, BSD library built for Python programming language.
❖ Pandas Offers high performance, easy to use data structures and data analysis tools.
❖ Pandas is the most popular library in the scientific python ecosystem for doing data analysis.
❖ It can read or write in many different data formats (integer, float, double, etc)
❖ It can calculate in all the possible ways data is organized i.e., across rows and down columns.
❖ It can easily select subsets of data from bulky data sets and even combine multiple datasets together.
It has functionality to find and fill missing data.
❖ It allows you to apply operations to independent groups within the data.
❖ It supports reshaping of data into different forms.
❖ It supports advanced time-series functionality (time series forecasting is the use of a model to predict
future values based on previously observed values)
❖ It supports visualization by integrating matplotlib and seaborn etc. Libraries.
❖ Pandas is the best at handling huge tabular data sets comprising different data formats.
Pandas Data Structure:
Data Structures refer to specialized way of storing data so as to apply a specific type of functionality
on them.
We can think Pandas data structures as enhanced versions of NumPy structured arrays in which the
rows and columns can be identified and accessed with labels rather than simple integer indices.
Out of many data structures of Pandas, two basic data structures – Series and DataFrame are
universally popular for their dependability.
(Pandas also supports Panel Data Structure, but it is not in syllabus)
SERIES
Series is a Pandas one-dimensional array containing a sequence of values of any data type (int, float,
list,string, etc) which by default have numeric data labels(index) starting from zero.
We can also assign values of other data types as index.
Ex:
A Series type object has two main components:
* An array of actual data
* An associated array of indexes or data labels.
Both components are one-dimensional arrays with the same length. The index is used to access individual
values.
We need to import pandas:
import pandas (or) import pandas as <identifier>
Ex: import pandas as pd
If we use numpy arrays, import numpy as np
Wrongly Given Import Statements:
Import Pandas (I and P are in Capitals)
import pandas as S.No (. or any special symbol is not allowed)
import pandas as if (keywords should not be given)
import pandas as 7rno (should not start with a digit)
(It can contain alphabets, digits and underscore only. It should not have any space, special symbol, keyword. It should
not start with a digit)
CREATING SERIES OBJECTS
A Series object can be created in many ways using pandas library’s Series( ).
First import pandas and numpy modules with import statements.
XII – IP (2025.2026 Material & Old CBSE Questions) 2 1. Series
If we import pandas as pd, we can use pd.Series( ) instead of pandas.Series( ).
(i) Creating of empty Series object:
Syntax: <Series Object>=pandas.Series( ) #S Upper case
Ex: S=pd.Series( )
Creates an empty Series S with no value, default datatype is float64.
Student’s Task
Create an empty series object with name “First”
(ii) Creating non-empty Series objects:
Specify arguments for data and indexes.
Syntax: <Series object>=pd.Series(data,index=idx, [dtype=<data type>]))
Here, idx is any valid Numpy type datatype, data is the data part of the Series object, it can be one of the
following:
⮚ A Python sequence
⮚ An ndarray
⮚ A Python dictionary
⮚ A scalar value
Note : If we do not give index, by default index array consists of the integers 0 through N-1 (N is the length of data).
(a) Specify data as Python Sequence:
Syntax: <Series Object>=Series(<any Python sequence>)
It will return an object of Series type.
Using Lists
>>> S=pd.Series([78,45,87])
>>> S
0 78
1 45
2 87
dtype: int64
>>> S=pd.Series([15.9,23.7])
>>> S
0 15.9
1 23.7
dtype: float64
>>> S=pd.Series([2.5,7.,9.2])
>>> S
0 2.5
1 7.0
2 9.2
dtype: float64
Note: It has taken 7. as 7.0
>>>S=pd.Series(["Welcome","To","my","School"])
>>> S
0 Welcome
1 To
2 my
3 School
dtype: object
>>> S=pd.Series([10,20.5])
>>> S
0 10.0
1 20.5
XII – IP (2025.2026 Material & Old CBSE Questions) 3 1. Series
dtype: float64
>>> S=pd.Series([2.7,5,"Welcome"])
>>> S
0 2.7
1 5
2 Welcome
dtype: object
Note: Left column displays index and right column displays values.
Student’s Task
Write a program to create a Series “Personal” with the following data and to display it.
Ramesh, 32, Akiveedu
Also predict the output.
Using Tuples
>>> S=pd.Series((15,20,25))
>>> S
0 15
1 20
2 25
dtype: int64
>>> S=pd.Series((15.5,17))
>>> S
0 15.5
1 17.0
dtype: float64
>>> S=pd.Series((10,15.5,"Welcome to World"))
>>> S
0 10
1 15.5
2 Welcome to World
dtype: object
String
>>> S=pd.Series("Welcome to World")
>>> S
0 Welcome to World
dtype: object
range() function
It generates a sequence.
Ex1: range(7) generates a sequence [0,1,2,3,4,5,6]
>>> S=pd.Series(range(7))
>>> S
0 0
1 1
2 2
3 3
4 4
5 5
6 6
dtype: int64
Ex2:
>>>S=pd.Series(range(1,10,3))
>>>S
0 1
1 4
XII – IP (2025.2026 Material & Old CBSE Questions) 4 1. Series
2 7
dtype: int64
Student’s Task
Write the output of the following statements:
(a) S=pd.Series(range(2,10,2))
(b) S=pd.Series(range(10,2,-1))
(c) S=pd.Series(range(2,10,-1))
Program to create a Series object using the Python sequence [10,15.9,"Welcome Friends"].
Solution:
import pandas as pd
S1=pd.Series([10,15.9,"Welcome Friends"])
print("Series Object is : ")
print(S1)
Output
Series Object is :
0 10
1 15.9
2 Welcome Friends
dtype: object
(b) Specify data as an ndarray:
N-Dimensional array (ndarray) in Numpy:
A numpy array is a grid of values, all of the same type, and is indexed by a tuple of non negative integers.
The number of dimensions is the rank of the array. The shape of an array is a tuple of integers giving
the size of the array along each dimension.
NumPy arrays facilitate advanced mathematical and other types of operations on large numbers of data.
NumPy is a Python library used for working with arrays.
Difference between NumPy Arrays and Series Objects:
ndarrays Series Objects
We can perform vectorised operations only if the In case of vectorised operations, the data of two Series
shapes of two ndarrays match, otherwise it returns an objects is aligned as per matching indexes and operation is
error (ValueError) performed on them and for non-matching indexes, NaN is
returned.
The indexes are always numeric starting from 0 Series objects can have any type of indexes, including
onwards numbers (not necessarily starting from 0), letters, labels,
strings, etc.
Using 1 dimensional nd array:
import pandas as pd
import numpy as np
ar=np.array([10,20.5,30,40,50]) #nd array
print(ar)
S=pd.Series(ar)
print(S)
Output
[10. 20.5 30. 40. 50. ]
0 10.0
1 20.5
2 30.0
3 40.0
4 50.0
dtype: float64
Ex2:
import numpy as np
import pandas as pd
array1 = np.array([10,20,30,40])
XII – IP (2025.2026 Material & Old CBSE Questions) 5 1. Series
print(array1)
S = pd.Series(array1, index = ["Mon","Tue", "Wed","Thu"])
print(S)
Output
[10 20 30 40]
Mon 10
Tue 20
Wed 30
Thu 40
dtype: int32
Ex3:
import numpy as np
import pandas as pd
A=np.array(['a','e','i','o','u'])
print(A)
S=pd.Series(A)
print(S)
Output
['a' 'e' 'i' 'o' 'u']
0 a
1 e
2 i
3 o
4 u
dtype: object
Using 2 dimensional nd array:
import numpy as np
list_of_lists = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
array1 = np.array(list_of_lists)
print(array1)
Note: With 2 dimensional nd array, We cannot create Series (Since Series is 1 dimensional), We can create
DataFrame.
We can also create ND Arrays, by using different functins like : arrange( ), linspace( ), tile( ), etc
arange( ) function
Numpy contains function arange ( ) with the following syntax:
arange(begin, end, update value)
Returns an array with evenly spaced elements as per the interval. The interval mentioned is half-opened i.e.
[Start, Stop)
Ex:np.arange(20,30,3) generates [20 23 26 29]
np.arange(20,30,2.5) generates [20. 22.5 25. 27.5] # end value excluded
Note: If Series created with NP Array Data (integers), its dtype is int32
Program to create a Series object using an ndarray which uses arrange function (numpy array) to
generate sequences between 20 and 30.
import pandas as pd
import numpy as np
nda1=np.arange(20,30,3)
nda2=np.arange(20,30,2.5)
print("Numpy array 1",nda1)
print("Numpy array 2",nda2)
S1=pd.Series(nda1)
S2=pd.Series(nda2)
XII – IP (2025.2026 Material & Old CBSE Questions) 6 1. Series
print("Series 1\n",S1)
print("Series 2\n",S2)
#We can directly give as #S1=pd.Series(np.arange(20,30,3))
Output
Numpy array 1 [20 23 26 29]
Numpy array 2 [20. 22.5 25. 27.5]
Series 1
0 20
1 23
2 26
3 29
dtype: int32
Series 2
0 20.0
1 22.5
2 25.0
3 27.5
dtype: float64
Some more examples (arange)
>>> n1=np.arange(10,20,2)
>>>n1
array([10, 12, 14, 16, 18])
>>> S1=pd.Series(n1)
>>>S1
0 10
1 12
2 14
3 16
4 18
dtype: int32
------------------------------------------------
>>> n2=np.arange(20,10,2)
>>>n2
array([], dtype=int32)
>>> S2=pd.Series(n2)
>>>S2
Series([], dtype: int32)
-----------------------------------------------
>>> n3=np.arange(5,2,-1)
>>>n3
array([5, 4, 3])
>>>S3=pd.Series(n3)
>>>S3
0 5
1 4
2 3
dtype: int32
----------------------------------------------
>>> n4=np.arange(-4,10,3)
>>>n4
array([-4, -1, 2, 5, 8])
>>>S4=pd.Series(n4)
>>>S4
0 -4
1 -1
2 2
3 5
XII – IP (2025.2026 Material & Old CBSE Questions) 7 1. Series
4 8
dtype: int32
----------------------------------------------
>>> n5=np.arange(2,10,2.2)
>>>n5
array([2. , 4.2, 6.4, 8.6])
>>>S5=pd.Series(n5)
>>>S5
0 2.0
1 4.2
2 6.4
3 8.6
dtype: float64
Student’s Task
Write a program
To create an ND Array “A”, which contains arrange() function.
Starting Data: 2
Last data to be taken : 20
Step value : 3
Predict the output of the above ND Array A.
Also it should create a Series “Test” using NP Array “A”. Predict the Series output also.
-------------------------------------------------------------------------------------------------------
linspace( ) function
Numpy contains function linspace( ) with the following syntax:
linspace (begin,end,no.of elements between these values)
end value includes
The linspace( ) method creates an array with evenly spaced elements over an interval.
Ex:np.linspace(20,30,6) generates [20. 22. 24. 26. 28. 30.]
Examples of linspace( ) function (of numpy)
>>>M1=np.linspace(2,10,7)
>>>M1
array([ 2. , 3.33333333, 4.66666667, 6. , 7.33333333, 8.66666667, 10. ])
>>>S1=pd.Series(M1)
>>>S1
0 2.000000
1 3.333333
2 4.666667
3 6.000000
4 7.333333
5 8.666667
6 10.000000
dtype: float64
-------------------------------------------------------------------------------------------------
>>>M2=np.linspace(-5,7,6)
>>>M2
array([-5. , -2.6, -0.2, 2.2, 4.6, 7. ])
>>>S2=pd.Series(M2)
>>>S2
0 -5.0
1 -2.6
2 -0.2
3 2.2
4 4.6
5 7.0
dtype: float64
Program to create a Series object using an ndarray which uses linspace function(numpy array) to
generate sequences between 20 and 30.
import pandas as pd
import numpy as np
XII – IP (2025.2026 Material & Old CBSE Questions) 8 1. Series
nda1=np.linspace(20,30,4)
nda2=np.linspace(20,30,6)
S1=pd.Series(nda1)
S2=pd.Series(nda2)
print("Series 1\n",S1)
print("Series 2\n",S2)
Output
Series 1
0 20.000000
1 23.333333
2 26.666667
3 30.000000
dtype: float64
Series 2
0 20.0
1 22.0
2 24.0
3 26.0
4 28.0
5 30.0
dtype: float64
Student’s Task
Write a program
To create an ND Array “B”, which contains linspace() function. Starting Data: 5 Last data to be taken : 30
No. of values : 6
Predict the output of the above ND Array B.
Also it should create a Series “Welcome” using ND Array “B”. Predict the Series Object output also.
Predict the Series output also.
tile( ) function
Numpy contains function tile ( ) for tiling a list for number of times.
The tile( ) method constructs an array by repeating arrays.
Ex: np.tile([5,10],3) generates [5,10,5,10,5,10]
Program to create a Series object using an ndarray that is created by tiling a list [5,10] for 3 times.
import numpy as np
import pandas as pd
S=pd.Series(np.tile([3,5],3))
print(S)
Output
Student’s Task
>>>p1=np.tile([1,2,3],3)
>>>p1
>>>S1=pd.Series(p1)
>>>S1
-----------------------------------------------------------
>>> S2=pd.Series(np.tile([2,5,9],2))
>>>S2
(c) Specify data as a Python Dictionary:
Keys of the dictionary object will becomes index of the Series and values of the dictionary become the data
of Series object. Indexes, which are created from keys may not be in the same order as we have typed them.
XII – IP (2025.2026 Material & Old CBSE Questions) 9 1. Series
Program to create a Series object using a dictionary that stores section wise toppers averages in each
section of class X in a school.
import pandas as pd
Stu={'A':89.5,'B':92.34,'C':91.5}
S=pd.Series(Stu)
print(S)
Output
A 89.50
B 92.34
C 91.50
dtype: float64
Student’s Task
Write a program to create a series object “Vowels” with 1,2,3,4,5 as keys and a,e,i,o,u as corresponding
values. Also write the output.
(d) Specifying data as scalar value:
The data can be in the form of a single value or a scalar value. If data is a scalar value, then the index
argument to Series( ) function must be provided.
The scalar value (given as data) will be repeated to match the length of index.
The index argument has to be a sequence of numbers or labels of any type.
>>> Marks=pd.Series(92)
>>> Marks
0 92
dtype: int64
>>> Marks=pd.Series(95,index=[11,12,13])
>>> Marks
11 95
12 95
13 95
dtype: int64
>>>Unknown=pd.Series('I don\'t know', index=['Un1','Un2'])
>>> Unknown
Un1 I don't know
Un2 I don't know
dtype: object
>>> Capital=pd.Series('Delhi',index=['State 1','State 2','State 3'])
>>> Capital
State 1 Delhi
State 2 Delhi
State 3 Delhi
dtype: object
>>> prizes=pd.Series(12,index=range(1,5))
>>> prizes
1 12
2 12
3 12
4 12
dtype: int64
>>>cer=pd.Series("Welcome",index=range(1,10,3))
>>> cer
1 Welcome
4 Welcome
7 Welcome
dtype: object
Program to create a Series object that stores the initial budget allocated (75000/- each ) for the four
quarters of the year: Q1, Q2, Q3, Q4.
import pandas as pd
XII – IP (2025.2026 Material & Old CBSE Questions) 10 1. Series
S=pd.Series(75000,index=['Q1','Q2','Q3','Q4'])
print(S) Output
Q1 75000
Q2 75000
Q3 75000
Q4 75000
dtype: int64
Student’s Task
Write a statement to create Series objects with the following data:
(a) A single value : 55
(b) Multiple Values : 10,20,30.
Take you desired index values
(c) Use a single value & range( ) function
CREATING SERIES OBJECTS
ADDITIONAL FUNCTIONALITY
(i) Specifying/Adding NaN values in a Series Object:
When we need to create a series object of a certain size but not having complete data, we can fill missing data with
a NaN (Not a Number) value. Legal empty value NaN is defined in NumPy module, we can use np.NaN to specify
missing value, or use None.
>>> import numpy as np
>>>S=pd.Series([10,"Hai",np.NaN,2.3,np.NaN])
>>> S
0 10
1 Hai
2 NaN
3 2.3
4 NaN
dtype: object
(ii) Specifying index(es) as well as data with Series( ):
Both values and indexes are sequences. None is taken by default, if you skip these parameters.
Syntax: <Series Object> = pandas.Series(data=None,index=None)
>>> stu=["Kamal","Mahesh","Jhansi"]
>>> marks=[76,82,79]
>>> S=pd.Series(data=marks, index=stu)
>>> S
Kamal 76
Mahesh 82
Jhansi 79
dtype: int64
Note: We can give data and index in any order.
If we do not use the data or index keywords, the first entered will be taken as data.
Ex:
>>> stu=["Kamal","Mahesh","Jhansi"]
>>> marks=[76,82,79]
>>>S1=pd.Series(stu,marks)
>>>S1
76 Kamal
82 Mahesh
79 Jhansi
dtype: object
>>>S4=pd.Series(index=marks,stu)
SyntaxError: positional argument follows keyword argument
>>>S4=pd.Series(stu,index=marks)
XII – IP (2025.2026 Material & Old CBSE Questions) 11 1. Series
>>>S4
76 Kamal
82 Mahesh
79 Jhansi
dtype: object
We can use loop for defining index sequence also.
>>> S1=pd.Series(range(1,20,4),index=[vowel
for vowel in 'aeiou'])
>>> S1
a 1
e 5
i 9
o 13
u 17
dtype: int64
Note: If specifying indexes explicitly using an index sequence, we must provide indexes equal to the number
of values in data array; providing too few or too many indices will lead to an error, the ValueError.
(iii) Specify Data Type along with data and index:
<Series Object>=pandas.Series(data=None, index=None, dtype=None)
None is the default value for different parameters taken in case no value is provided for a parameter.
If we do not specify datatype, the nearest datatype to store the given values will be taken. We can
specify our own datatype by specifying a NumPy datatype with dtype attribute.
>>> stu=["Kamal","Mahesh","Jhansi"]
>>> marks=[76,82,79]
>>> S=pd.Series(data=marks,index=stu,dtype=np.float64)
>>> S
Kamal 76.0
Mahesh 82.0
Jhansi 79.0
dtype: float64
(iv) Using a Mathematical Function/Expression to Create Data Array in Series( ):
<Series Object>=pandas.Series(index=None, data=<function/expression>)
a=[5,10,15,20]
>>> S=pd.Series(data=a*2) #Python list a replicates 2 times
>>> S
0 5
1 10
2 15
3 20
4 5
5 10
6 15
7 20
dtype: int64
>>> S=pd.Series(index=a, data=a*2)
ValueError: Length of values (8) does not match length of index (4)
>>> m=np.arange(9,13)
>>> m
array([ 9, 10, 11, 12])
>>> S2=pd.Series(index=m,data=m*2)
>>> S2
9 18
10 20
11 22
12 24
XII – IP (2025.2026 Material & Old CBSE Questions) 12 1. Series
dtype: int32
>>> S3=pd.Series(index=m,data=m**2)
>>> S3
9 81
10 100
11 121
12 144
dtype: int32
Indices need not be unique in Pandas Series Object. This will only cause an error if/when you perform an
operation that requires unique indices.
>>> val=[10.5,12,"Welcome"]
>>> S=pd.Series(data=val,index=['a','b','a'])
>>> S
a 10.5
b 12
a Welcome
dtype: object
Accessing a Series Object and its Elements
SERIES - SLICES
We can access Series indexes separately, data separately, also can access individual elements and slices.
Let us take some example Series Objects.
>>>S1=pd.Series(data=[5,6,7,8,9,10,11,12], index=['May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])
>>> S2=pd.Series(data=[75,72,89], index=['Raj','Kamal','Nani'])
>>> S3=pd.Series([87,99,52],index=[11,12,13])
(a) Accessing/Modifying Individual Elements using Indexing:
With index value or with its position.
Syntax: <Series Object name>[<valid index>]
>>> S1['Jul']
7
Note:
(1) If the Series object has duplicate indexes, then giving an index with the Series object will return all the entries with that
index.
(2) If the indexes are string type, then it will work with position value also, otherwise, KeyError will come.
>>> S1[2]
7
>>> S3[11]
87
>>> S3[0]
KeyError
Note: >>S1[0]=13 will change the value of “May” as 13 instead of 5.
More than one element of a series can be accessed using a list of positional integers or a list of index
labels as shown in the following examples:
XII – IP (2025.2026 Material & Old CBSE Questions) 13 1. Series
>>> S1[['Jul','Dec','May']]
>>>S1[[7,0,3]]
(b) Extracting Slices from Series Object:
Slicing takes place position wise and not the index wise in a series object.
All individual elements have position numbers starting form 0 onwards.
Syntax: <object>[start:end:step). (end value is excluding)
The slice object of a Series object is also a pandas Series type object.
Ex: S=pd.Series(data=[21,22,23,24,25,26,27,28,29, 30,31,32], index=['Jan','Feb','Mar','Apr','May',
'Jun','Jul','Aug','Sep','Oct','Nov','Dec'])
>>>S[1:5] #position wise, not index wise
Feb 22
Mar 23
Apr 24
May 25
dtype: int64
>>>S[10:5]
Series([], dtype: int64)
>>>S[15:20]
Series([], dtype: int64)
>>>S[2:10:2]
Mar 23
XII – IP (2025.2026 Material & Old CBSE Questions) 14 1. Series
May 25
Jul 27
Sep 29
dtype: int64
>>>S[7:2:-1]
Aug 28
Jul 27
Jun 26
May 25
Apr 24
dtype: int64
>>>S[10:1:-2]
Nov 31
Sep 29
Jul 27
May 25
Mar 23
dtype: int64
>>>S[:]
Jan 21
Feb 22
Mar 23
Apr 24
May 25
Jun 26
Jul 27
Aug 28
Sep 29
Oct 30
Nov 31
Dec 32
dtype: int64
>>>S[:5]
Jan 21
Feb 22
Mar 23
Apr 24
May 25
dtype: int64
>>>S[ :8:2]
Jan 21
Mar 23
May 25
Jul 27
dtype: int64
>>>S[ : :1]
Jan 21
Feb 22
Mar 23
Apr 24
May 25
Jun 26
XII – IP (2025.2026 Material & Old CBSE Questions) 15 1. Series
Jul 27
Aug 28
Sep 29
Oct 30
Nov 31
Dec 32
dtype: int64
>>>S[ : :3]
Jan 21
Apr 24
Jul 27
Oct 30
dtype: int64
>>>S[ : :-1] #slice with values reversed
Dec 32
Nov 31
Oct 30
Sep 29
Aug 28
Jul 27
Jun 26
May 25
Apr 24
Mar 23
Feb 22
Jan 21
dtype: int64
>>>S[::-2]
Dec 32
Oct 30
Aug 28
Jun 26
Apr 24
Feb 22
dtype: int64
>>>S[ :5:-2]
Dec 32
Oct 30
Aug 28
dtype: int64
>>>S[ :5:2]
Jan 21
Mar 23
May 25
dtype: int64
>>>S[-8:7]
May 25
Jun 26
Jul 27
dtype: int64
>>>S[-10:10:2]
Mar 23
XII – IP (2025.2026 Material & Old CBSE Questions) 16 1. Series
May 25
Jul 27
Sep 29
dtype: int64
>>>S[2::3]
Mar 23
Jun 26
Sep 29
Dec 32
dtype: int64
>>>S[10::-3]
Nov 31
Aug 28
May 25
Feb 22
dtype: int64
Note: We can also use slicing to modify the values of series elements as shown in the following example:
>>> S[1:4]=10
Note: Observe that updating the values in a series using slicing also excludes the value at the end index
position. But, it changes the value at the end index label when slicing is done using labels.
>>>S['Sep':'Nov']=77
Student’s Task
Consider the following Series “E”, and answer the questions based on Slicing.
XII – IP (2025.2026 Material & Old CBSE Questions) 17 1. Series
E=pd.Series(['CT1','CT2','CT3','CT4','T1','PT1','PT2', 'PT3','PT4','PT5','PT6','PT7','PB1','PB2','Pra','Board'],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'])
(a) E[2:10] (b) E[3:12:2] (c) E[-12:10:3] (d) E[4:11:2] (e) E[4:11:-2] (f) E[10:2:-3]
(g) E[10:2:3] (h) E[10: ] (i) E[10: :-1] (j) E[::-3]
(c) Accessing Data through loc (labelled based indexing):
The loc function in Pandas Series is used for label-based indexing and retrieval of data. It allows you to
access specific elements or subsets of the Series based on their index labels.
Syntax: seriesobject.loc[indexer]
indexer can be: A single label, A list of labels, A boolean array of the same length as the Series, A slice
object to select a range of labels
Ex: import pandas as pd
lst=[11,22,33,44,55,66]
index=['a','b','c','d','e','f']
s=pd.Series(lst,index)
print(s)
print(s.loc['b':'e'])
print(s.loc['c'])
print(s.loc[['d','c','e']])
print(s.loc[s>30])
Output
a 11
b 22
c 33
d 44
e 55
f 66
dtype: int64
b 22
c 33
d 44
e 55
dtype: int64
33
d 44
c 33
e 55
dtype: int64
c 33
d 44
e 55
f 66
dtype: int64
(d) Accessing Data through iloc (Integer based indexing):
XII – IP (2025.2026 Material & Old CBSE Questions) 18 1. Series
The iloc function in Pandas is used for integer-based indexing of a Series. It allows you to access and
manipulate data elements based on their position within the Series, rather than their labels. This can be useful
when you need to select specific elements based on their order or when the labels are not meaningful for the
task at hand.
Syntax: seriesobject.iloc[position]
Example Program for iloc:
import pandas as pd
lst=[11,22,33,44,55,66]
index=['a','b','c','d','e','f']
s=pd.Series(lst,index)
print(s)
print(s.iloc[1:4]) # for 1 to 3 index position – Slice of elements
print(s.iloc[2]) # for a single element
print(s.iloc[:3]) # for first 3 index values
print(s.iloc[: :-1]) # Reverse Order
Output
a 11
b 22
c 33
d 44
e 55
f 66
dtype: int64
b 22
c 33
d 44
dtype: int64
33
a 11
b 22
c 33
dtype: int64
f 66
e 55
d 44
c 33
b 22
a 11
dtype: int64
OPERATIONS ON SERIES OBJECT
(a) Modifying Elements of Series Object:
Syntax: <SeriesObject>[<index>]=<new data value>
Above assignment will change the data value of the given index in the Series object.
<SeriesObject>[start:stop]=<new data value>
Above assignment will replace all the values falling in given slice.
>>>S2=pd.Series(data=[75,72,89],index=['Raj', 'Kamal','Nani'])
>>> S2
Raj 75
Kamal 72
Nani 89
dtype: int64
>>> S2["Raj"]=94
>>> S2[1]=99
>>> S2
Raj 94
Kamal 99
Nani 89
dtype: int64
XII – IP (2025.2026 Material & Old CBSE Questions) 19 1. Series
>>> S1[1:6]=25
(b) Renaming Indexes:
Syntax:<Object>.index=<new index array>
>>> S3=pd.Series([87,99,52],index=[11,12,13])
>>> S3
11 87
12 99
13 52
dtype: int64
>>> S3.index=['First','Second','Third']
>>> S3
First 87
Second 99
Third 52
dtype: int64
>>> S3.index=['One','Two']
ValueError
We can also change individual index:
Ex: To change index “First” to “One”.
S3 = S3.rename(index={'First': 'One'})
(c) head( ) & tail( )function:
head( ) function is used to fetch first n rows from a Pandas object and tail( ) function returns last n rows from
a Pandas object.
Syntax: <pandas object>.head([n])
<pandas object>.tail([n])
Note: If you do not provide any value for n, the head( ) and tail( ) will return first 5 and last 5 rows.
>>> S1
May 5
Jun 6
Jul 7
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12
dtype: int64
>>> S1.head(3)
May 5
Jun 6
Jul 7
dtype: int64
XII – IP (2025.2026 Material & Old CBSE Questions) 20 1. Series
>>> S1.head()
May 5
Jun 6
Jul 7
Aug 8
Sep 9
dtype: int64
>>> S1.head(77)
May 5
Jun 6
Jul 7
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12
dtype: int64
>>> S1.head(-2)
May 5
Jun 6
Jul 7
Aug 8
Sep 9
Oct 10
dtype: int64
>>> S1.tail(3)
Oct 10
Nov 11
Dec 12
dtype: int64
>>> S1.tail()
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12
dtype: int64
>>> S1.tail(22)
May 5
Jun 6
Jul 7
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12
dtype: int64
>>> S1.tail(-3)
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12
dtype: int64
XII – IP (2025.2026 Material & Old CBSE Questions) 21 1. Series
(d) Vector operations on Series Object:
Vector operations means that if we apply a function or expression, then it is individually applied on each
item of the object. As Series Objects are built upon NumPy arrays (ndarrays), they also support vectorised
operations just like ndarrays.
>>> S=pd.Series([2,3,4,5])
>>> S
0 2
1 3
2 4
3 5
dtype: int64
>>> S+2
0 4
1 5
2 6
3 7
dtype: int64
>>> S-1
0 1
1 2
2 3
3 4
dtype: int64
>>> S*3
0 6
1 9
2 12
3 15
dtype: int64
>>> S/2
0 1.0
1 1.5
2 2.0
3 2.5
dtype: float64
>>> S>3
0 False
1 False
2 True
3 True
dtype: bool
>>>S[S>3]
2 4
3 5
dtype:int64
>>> S5=pd.Series([2,3,4,5])
>>> S6=S5**2
>>> S6
0 4
1 9
2 16
3 25
dtype: int64
XII – IP (2025.2026 Material & Old CBSE Questions) 22 1. Series
Student’s task
M=pd.Series(data=[1,2,3,4,5,6,7], index=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'])
Try following for the Series Object M.
(i) M+5 (ii) M-4 (iii) M*3 (iv) M/2 (v) M//2 (v) M%2
(vi) M**2 (vii) M>3 (vii) M[M>4]
(e) Arithmetic on Series Object
(Mathematical Operations on Series)
We can do arithmetic like addition, subtraction, division, etc with two Series objects and it will calculate result
on two corresponding items of the two objects given in expression.
While performing mathematical operations on series, index matching is implemented and all missing
values are filled in with NaN(not a number) by default.
If the data items of the two matching indexes are not compatible for the operation, it will return NaN.
We can do..
(i) Addition of two Series (ii) Subtraction of two Series
(iii) Multiplication of two Series (iv) Division of two Series
Consider 3 Series: Ob1, Ob2, Ob3
>>>Ob1=pd.Series([-5,4,2,5])
>>>Ob2=pd.Series([2.5,-1.0,5.0])
>>>Ob3=pd.Series([2,4,-1,7])
(i) Addition of two Series :
It can be done in two ways.
In the first method, two series are simply added together, as shown in the following code.
Following Table 1 shows the detailed values that were matched while performing the addition. Note here that
the output of addition is NaN if one of the elements or both elements have no value.
Table 1 : Details of Addition of Two Series
index Value from Ob1 Value from Ob2 Ob1+Ob2
0 -5 2.5 -2.5
1 4 -1.0 3.0
2 2 5.0 7.0
3 5 NaN
XII – IP (2025.2026 Material & Old CBSE Questions) 23 1. Series
The second method is applied when we do not want to have NaN values in the output. We can use the series method
add( ) and a parameter fill_value to replace missing value with a specified value. That is, calling Ob1.add(Ob2) is
equivalent to calling Ob1+Ob2, but add() allows explicit specification of the fill value for any element in Ob1 or Ob2
that might be missing, as shown in Table 2.
>>> Ob1.add(Ob2, fill_value=0)
Table 2 : Details of addition of two series using add() method
index Value from Ob1 Value from Ob2 Ob1+Ob2
0 -5 2.5 -2.5
1 4 -1.0 3.0
2 2 5.0 7.0
3 5 0 5
>>> Ob4=Ob1.add(Ob2,fill_value=75)
Note:
Just like addition, subtraction, multiplication and division can also be done using corresponding mathematical
operators or explicitly calling of the appropriate method.
(B) Subtraction of two Series:
>>> Ob4=pd.Series(["Welcome","to","World"])
>>> Ob5=pd.Series(["I","am","Human"])
XII – IP (2025.2026 Material & Old CBSE Questions) 24 1. Series
>>> Ob1+Ob4
TypeError: unsupported operand type(s) for +: 'int' and 'str'.
Note : If the indexes are not matched, then NaN values will come.
Note: When we perform airthmetic operations on two Series type objects, the data is aligned on the basis of matching
indexes (this is called Data alignment in Pandas object) and then performed arithmetic; for non-overlapping indexes,
the arithmetic operations result as a NaN (Not a Number).
We can store the result of object arithmetic in another object, which will also be a Series object.
>>>Ob3=Ob1+Ob2
(C) Multiplication of two Series:
>>> Ob1*Ob2
(D) Division of two Series:
(f) Filtering Entries: We can filter entries from a Series object using expressions that are of Boolean type
(ie the expressions that results Boolean value True/False).
When we apply a comparison operator directly on a Pandas Series object, then it works like vectorized
operation and applies this check on each individual element of Series object.
Syntax: <Series Object>[[<Boolean Expression on Series Object>]
Ex:
>>> S=pd.Series([5,10,20,25,30])
Series Obj Vectorized Operation Filtered Result
XII – IP (2025.2026 Material & Old CBSE Questions) 25 1. Series
(g) Sorting Series Values:
We can sort the values of a Series object on the basis of values and indexes.
Sorting on the Basis of Values:
Syntax: <Series object>. sort_values([ascending=True/False])
The argument ascending is optional and if skipped, it takes the value True by default.
>>> S=pd.Series([2500,1200,1700,-500,700])
>>> S.sort_values(ascending=True)
# or >>> S.sort_values( )
>>> S.sort_values(ascending=False)
# will display in descending order
Note : To make the sorted values permanent in the Series object, use “inplace=True”.
Ex:
>>> S.sort_values(ascending=True,inplace=True)
# or >>> S.sort_values(inplace=True)
# will sort the Series in ascending order permanently.
Sorting on the Basis of Indexes: sort_index()
Syntax: <Series object>.sort_index([ascending=True/False])
The argument ascending is optional and if skipped, it takes the value True by default.
Ex: Obj=pd.Series([2500,-500,3500,1500], index=['C','B','D','A'])
Note : To make the sorted values permanent in the Series object, use “inplace=True”.
>>>Obj.sort_index(ascending=False, inplace=True)
XII – IP (2025.2026 Material & Old CBSE Questions) 26 1. Series
(h) Reindexing:
To create a similar object with different order of same indexes.
<Series Object>=<Object>.reindex (<sequence with new order of indexes>)
With this, the same data values and their indexes will be stored in the new object as per the defined
order of index in the reindex( ).
>>> Obj2=Obj1.reindex(['C','A','B','D'])
>>> Obj3=Obj1.reindex(['D','B','Mar','Apr'])
(i) Dropping Entries from an Axis:
To remove an entry from Series object use drop( ).
Syntax:
<Series Object>.drop(<index to be removed>)
>>> Obj.drop('C',inplace=True)
Differences between Series and DataFrame
Property Series DataFrame
Dimensions 1 Dimensional 2-Dimensional
Type of Homegeneous, i.e., all the elements must be of Heterogeneous, i.e., a DataFrame object can have
Data same type in a Series object elements of different data types
Value mutable, i.e., their elements value can Value mutable, i.e., their elements value can change
Mutability change
Size-immutable, i.e., size of a Series object, Size-mutable,i.e., size of a Dataframe object, once
once created, cannot change. If we want to created, can change in place. That is, you can add/drop
add/drop an element, internally a new Series elements in an existing dataframe object.
object will be created
XII – IP (2025.2026 Material & Old CBSE Questions) 27 1. Series
Pandas Series Vs NumPy ndarray:
Pandas supports non-unique index values.
A basic difference between Series and ndarray is that operations between Series automatically align the data
based on the label. Thus, we can write computations without considering whether all Series involved have the same
label or not.
The result of an operation between unaligned Series (i.e. where the corresponding labels of the series are not
the same or are not in the same order) will have the union of the indexes involved. If a label is not found in one Series
or the other, the result will be marked as missing NaN. Being able to write code without doing any explicit data
alignment grants immense freedom and flexibility in interactive data analysis and research.
Difference between Pandas Series and NumPy Arrays
Pandas Series NumPy Arrays
In series we can define our own labeled index to NumPy arrays are accessed by their integer
access elements of an array. These can be position using numbers only.
numbers
or letters.
The elements can be indexed in descending order The indexing starts with zero for the first
also. element and the index is fixed.
If two series are not aligned, NaN or missing There is no concept of NaN values and if there
values are no matching values in arrays, alignment
are generated. fails.
Series require more memory. NumPy occupies lesser memory.
Series Object Attributes
When we create a Series type object, all information related to it is available through attributes.
Syntax: <Series object>.<attribute name>
(Attributes doesn’t contain parenthesis, whereas functions should contain parenthesis)
Some common attributes
Attribute Description
index The index(axis labels) of the Series
index.name Name of the index. Can be used to assign new name to index.
values Return Series as ndarray or ndarray-like (data) depending on the dtype
dtype Return the dtype object of the underlying data (datatype)
shape Return a tuple of the shape of the underlying data
nbytes Return the number of bytes in the underlying data
ndim Return the number of dimensions of the underlying data
size Return the number of elements in the underlying data
itemsize Return the size of the dtype of the item of the underlying data. But in present python version, it
is not working.
hasnans Return True if there are any NaN values; otherwise return False
empty Return True if the Series object is empty, false otherwise.
name Return or assign name to Series object
# NCERT Text Book Given – name, index.name, values, size, empty only.
Consider the following Series Object:
>>> Marks=[34,33,np.NaN,38,40]
>>> Exams=["CT1","CT2","CT3","CT4","CT5"]
>>> S=pd.Series(Marks, index=Exams)
>>> S
CT1 34.0
CT2 33.0
CT3 NaN
CT4 38.0
CT5 40.0
dtype: float64
(i) index :
>>> S.index
Index(['CT1', 'CT2', 'CT3', 'CT4', 'CT5'], dtype='object')
XII – IP (2025.2026 Material & Old CBSE Questions) 28 1. Series
(ii) index.name
>>> S.index.name="Test"
>>>S.index.name
'Test'
>>> S.index
>>>Index(['CT1', 'CT2', 'CT3', 'CT4', 'CT5'], dtype='object', name='Test')
(iii) values:
>>> S.values
array([34., 33., nan, 38., 40.])
(iv) dtype:
>>> S.dtype
dtype('float64')
(v) shape:
>>> S.shape
(5, )
(vi) nbytes:
>>> S.nbytes #5 elements X 4 bytes for float
40
(vii) ndim:
>>> S.ndim # Series is One Dimensional
1
(viii) size: >>> S.size # 5 elements
5
(ix) itemsize: In new versions, this property was removed.
AttributeError: 'Series' object has no attribute 'itemsize'
(x) hasnans: >>> S.hasnans
True
(xi) empty: >>> S.empty
False
(xii) name
>>> S.name="MySeries"
>>>S.name
'MySeries'
>>>S
CT1 34.0
CT2 33.0
CT3 NaN
CT4 38.0
CT5 40.0
Name: MySeries, dtype: float64
Other examples related to index
>>> S3=pd.Series(data=np.arange(5,25,4))
>>> S3.index
RangeIndex(start=0, stop=5, step=1)
>>> a=np.arange(9,13)
>>> S4=pd.Series(index=a,data=a*2)
>>> S4.index
Index([9, 10, 11, 12], dtype='int32')
>>>S4
9 18
10 20
11 22
12 24
dtype: int32
XII – IP (2025.2026 Material & Old CBSE Questions) 29 1. Series
Some functions
Function Use
len( ) To get total number of elements (including NaN values)
count( ) To get the count of non-NaN values in a series object
type( ) To know the data type of an object
(Note: Count( ) function is important )
>>> len(S)
5
>>> S.count()
4
>>> type(S)
<class 'pandas.core.series.Series'>
Note: In the same statement, we can work with 2 or more attributes of the Same Series or different also.
>>>S1=pd.Series([10,20,30])
>>>S1
0 10
1 20
2 30
dtype: int64
>>>S2=pd.Series(['a','e','i','o','u'], index=[100,200,300,400,500])
>>>S2
100 a
200 e
300 i
400 o
500 u
dtype: object
>>>S1.shape,S2.shape
((3,), (5,))
>>>print(S1.shape,S2.shape)
(3,) (5,)
>>>S1.ndim,S2.nbytes
(1, 40)
>>>print(S1.ndim,S2.nbytes)
1 40
Student’s Task
>>>Veg=pd.Series(['Onion','Carrot','Beetroot', 'Potato'],[30,70,50,20])
>>> Veg
30 Onion
70 Carrot
50 Beetroot
20 Potato
dtype: object
For the above Series “Veg”, Work with the above 12 attributes and 3 functions. Also write outputs.
XII – IP (2025.2026 Material & Old CBSE Questions) 30 1. Series
XII – IP – CBSE OLD QUESTIONS
SERIES
1.CBSE BOARD PAPER::2024.25
1. State whether the following statement is True or False:
In Python, we cannot create an empty DataFrame
2. What is the default index type for a Pandas Series if not explicitly specified ?
(A) String (B) List (C) Numeric (D) Boolean
3.Which of the following data structure is used for storing one-dimensional labelled data in Python Pandas ?
(A) Integer (B) Dictionary (C) Series (D) DataFrame
4. Which of the following Python statements will be used to select a specific element having index as
points, from a Pandas Series named ser ?
(A) ser.element(points) (B) ser.select(points)
(C) ser[points] (D) ser.show(points)
5. Which of the following libraries defines an ndarray in Python ?
(A) pandas (B) numpy (C) matplotlib (D) scipy
6. Rohit is trying to create a Pandas Series from scalar values. His code has some mistakes.
Rewrite the correct code and underline the corrections made.
import pandas
data = [50, 15, 40]
series = pd.series(data, Index=['x', 'y', 'z'])
Print(series)
7. Write a Python program to create a Pandas Series as shown below from an ndarray containing the
numbers 10, 20, 30, 40, 50 with corresponding indices 'A', 'B', 'C', 'D', 'E'.
CBSE Board Paper :: 2024.25 (ANSWERS)
1. False 2. C. Numeric 3. (C) Series 4. (C) ser[points] 5. (B) numpy
6. import pandas as pd
data=[50,15,40] #OR data = <any numeric value>
series=pd.Series(data, index=['x', 'y', 'z'])
print(series)
7. import pandas as pd
import numpy as np
data = np.array([10,20,30,40,50]) # np.arange(10,60,10)
s = pd.Series(data,index=['A', 'B', 'C', 'D', 'E'])
print(s)
OR
import pandas as pd
import numpy as np
L1=np.array([10,20,30,40,50])
L2=np.array(['A','B','C','D','E'])
S1=pd.Series(L1,index=L2)
print(S1)
XII – IP (2025.2026 Material & Old CBSE Questions) 31 1. Series
2.CBSE COMPARTMENT PAPER::2024.25
1. In Pandas library of Python, a one-dimensional array containing a sequence of values of any datatype is
known as :
(A)DataFrame (B)Histogram (C) Series (D)Panel
2. What will be the output of the following Python code ?
import pandas as pd
dd={'Jan':31,'Feb':28,'Mar':31,'Apr':30}
rr=pd.Series(dd)
print(rr)
A)
Jan 31
Feb 28
Mar 31
Apr 30 dtype: int64
B)
Jan Feb Mar Apr
31 28 31 30
dtype:int64
C)
Jan – 31
Feb – 28
Mar – 31
Apr – 30 dtype: int64
D)
Jan Feb Mar Apr
| | | |
31 28 31 30
dtype: int64
3. Find the output of the following Python code :
import pandas as pd
vaccine_qty=pd.Series([10,16,1],index=["Typhoid","Tetanus","Hepatitis"])
cost=pd.Series([200,500,800],index=["Typhoid","Tetanus", "Flu"])
print(vaccine_qty + cost)
CBSE Compartment Paper :: 2024.25 (ANSWERS)
1. Series 2. A
3.
Flu NaN
Hepatitis NaN
Tetanus 516.0
Typhoid 210.0
dtype: float64
3.CBSE SAMPLE PAPER::2024.25
SERIES ( 9 Marks)
2 or 3 MCQs.
Theory questions
Series creation using different methods
Complete the missing code of Series
Series – Output (List & Tuples – Replication,
Creation of Series with List/Tuple multiplication – Replication,
ND Array and Series – Multiplication of corresponding values.
XII – IP (2025.2026 Material & Old CBSE Questions) 32 1. Series
1. State whether the following statement is True or False:
Slicing can be used to extract a specific portion from a Pandas Series.
A) True
15. While creating a Series using a dictionary, the keys of the dictionary become:
(A)Values of the Series (B) Indices of the Series
(C) Data type of the Series (D) Name of the Series
A) (B) Indices of the Series
22. What is a Series in Python Pandas? Also, give a suitable example to support your answer. (2m)
A) A Series is a one-dimensional array containing a sequence of values of any data type (int, float, list,
string, etc) which by default have numeric data labels starting from zero. We can imagine a Pandas Series as
a column in a spreadsheet. An example of a series containing the names of students is given below:
Index Value
0 Arnab
1 Samridhi
2 Ramit
3 Divyam
22. (OR)B) What does the term 'library' signify in Python? Mention one use for each of the following
libraries: • Pandas • Matplotlib
A) Library: A collection of modules providing functionalities for specific tasks.
Pandas: Used for data analysis
Matplotlib: Used for creating plots
28. B) Complete the given Python code to get the required output (ignore the dtype attribute) as (2m)
Output:
Tamil Nadu Chennai
Uttar Pradesh Lucknow
Manipur Imphal
Code:
import _______ as pd
data = ['Chennai','_______','Imphal']
indx = ['Tamil Nadu','Uttar Pradesh','Manipur']
s = pd.Series(_______, indx)
print(_______)
A)
import pandas as pd
data = ['Chennai', 'Lucknow', 'Imphal']
indx = ['Tamil Nadu','Uttar Pradesh','Manipur']
s = pd.Series(data, indx)
print(s)
30. B.(OR) Write a Python Program to create a Pandas Series as shown below using a dictionary. Note that
the left column indicates the indices and the right column displays the data. (3m)
A) import pandas as pd
data = {'Russia':'Moscow','Hungary':'Budapest','Switzerland':'Bern'}
s = pd.Series(data)
print(s)
4.CBSE BOARD PAPER::2023.24
10. What will be the output of the following Python code ?
import pandas as pd
dd= { 'One':1, 'Two':2, 'Three':3, 'Seven':7}
rr=pd.Series(dd)
rr['Four']=4
print(rr)
XII – IP (2025.2026 Material & Old CBSE Questions) 33 1. Series
(i)
One 1
Two 2
Three 3
Seven 7
dtype: int64
(ii)
One 1
Two 2
Three 3
Four 4
Seven 7
dtype: int64
(iii)
Four 4
One 1
Two 2
Three 3
Seven 7
dtype: int64
(iv)
One 1
Two 2
Three 3
Seven 7
Four 4
dtype: int64
12. Which of the following command will not show first five rows from the Pandas series named Sl ?
(i) Sl[0:5] (ii) Sl.head() (iii) Sl.head(5) (iv) Sl.head[0:5]
22. Find the output of the following Python code :
import pandas as pd
com=pd.Series([45,12,15,200],index=['mouse','printer', 'webcam','keyboard'])
print(com[l:3])
A) printer 12
webcam 15
dtype: int64
5.CBSE Additional Practice Paper ::2023.24
15. A Series is a one dimensional array containing a sequence of values of any data type (int, float, list, string, etc),
having by default have ________ data labels.
a. alphanumeric b. string c. decimal d. numeric
24. Find the output of the following code:
import pandas as pd
lst1=[20,35,40]
ser1=pd.Series([20,35,40])
print(lst1+lst1)
print(ser1+ser1)
27. Complete the given Python code to get the required output as "California”:
import_____________as pd
data={'Yosemite':'California','Yellowstone':'Wyoming',
'Glacier':'Montana','RockyMountain':'Colorado'}
national_parks=pd.Series(_____________)
print(national_parks _________)
CBSE Additional Practice Paper :: 2023.24 (ANSWERS)
XII – IP (2025.2026 Material & Old CBSE Questions) 34 1. Series
15. d
24. [20, 35, 40, 20, 35, 40]
0 40
1 70
2 80
27.
import pandas as pd
data = {'Yosemite': 'California', 'Yellowstone': 'Wyoming', 'Glacier': 'Montana', 'Rocky Mountain': 'Colorado'}
national_parks = pd.Series(data)
print(national_parks['Yosemite'])
6.CBSE SAMPLE PAPER::2023.24
10. Which of the following command will show the last 3 rows from a Pandas Series named NP?
i. NP.Tail( ) ii. NP.tail(3) iii. NP.TAIL(3) iv. All of the above
12. In Python Pandas, while performing mathematical operations on series, index matching is implemented and all
missing values are filled in with _____by default.
i. Null ii. Blank iii. NaN iv. Zero
18. Assertion (A):- To use the Pandas library in a Python program, one must import it.
Reasoning (R): - The only alias name that can be used with the Pandas library is pd.
i. Both A and R are true and R is the correct explanation for A
ii. Both A and R are true and R is not the correct explanation for A
iii. A is True but R is False
iv. A is false but R is True
22. Predict the output of the given Python code:
import pandas as pd
list1=[-10,-20,-30]
ser = pd.Series(list1*2)
print(ser)
24. Complete the given Python code to get the required output as: Rajasthan
import _________ as pd
di = {'Corbett': 'Uttarakhand', 'Sariska': 'Rajasthan',
'Kanha': 'Madhya Pradesh’, 'Gir':'Gujarat'}
NP = ___________. Series ( _____ )
print(NP[ ___________ ])
CBSE SAMPLE PAPER :: 2023.24 (ANSWERS)
10. ii. NP.tail(3)
12. iii. NaN
18. iii. A is True but R is False
22. 0 -10
1 -20
2 -30
3 -10
4 -20
5 -30
24. import pandas as pd
di = {'Corbett': 'Uttarakhand', 'Sariska':'Rajasthan', 'Kanha': 'Madhya Pradesh','Gir':'Gujarat'}
NP = pd.Series( di)
print(NP[ 'Sariska'])
7.CBSE COMPARTMENT::2022.23
11. Which of the following is a one-dimensional array containing a sequence of values in Python ?
(a) Relation (b) DataFrame (c) Series (d) Square
12. In Python Pandas, head(n) method returns the first n members of the series.What is the default value of n?
(a) 2 (b) 3 (c) 4 (d) 5
24. What will be the output of the following code ?
XII – IP (2025.2026 Material & Old CBSE Questions) 35 1. Series
import pandas as pd
S1=pd.Series(data=[1,7])
S2=pd.Series(S1+S1)
print(S2)
27. Write a program in Python Pandas to create a
series “car” from the following Dictionary :
dic={"Model":["Samurai","Accord","CR-V",”Nexon"], "Brand":["Suzuki","Honda","Honda","Tata"],
"Make":[1993,1997,1997,2021]}
ANSWERS
11. (c) Series
12. (d) 5
24. 0 2
1 14
27.
import pandas as pd
dic={"Model":["Samurai", "Accord", "CR-V",”Nexon"], "Brand": ["Suzuki", "Honda", "Honda", "Tata"],
"Make": [1993, 1997, 1997, 2021] }
car = pd.Series(dic)
8. CBSE BOARD PAPER::2022.23
10. What will be the output of the following code?
import pandas as pd
myser=pd.Series([0, 0, 0])
print(myser)
(i) 0 0 (ii) 0 1
0 0 0 1
0 0 0 2
(iii) 0 0 (iv) 0 0
1 0 1 1
2 0 2 2
18. Assertion (A) : The output of addition of two series will by NAN, if one of the elements or both the elements have
no value(s).
Reason (R): While performing mathematical operations on a series, by default all missing values are filled in with 0.
22. Write a Python program to create a series object, country using a list that stores the capital of each country.
Note: Assume four countries to be used as index of the series object are India, UK,
Denmark, and Thailand having their capitals as New Delhi, London, Copenhagen, and Bangkok respectively.
24. What will be the output of the following code:
import pandas as pd
s1=pd.Series(data=2*(3,10))
print(s1)
CBSE BOARD PAPER :: 2022.23 (ANSWERS)
10) (iii) 0 0
1 0
2 0
18) (A) is true but (R) is false.
22)
import pandas as pd
capital = ['New Delhi', 'London', 'Copenhagen', ‘Bangkok']
country = pd.Series(capital, index = ['India', 'UK', 'Denmark', 'Thailand'])
24) 0 3
1 10
2 3
3 10
9. CBSE SAMPLE PAPER::2022.23
XII – IP (2025.2026 Material & Old CBSE Questions) 36 1. Series
10. To display last five rows of a series object ‘S’,
you may write:
i. S.Head() ii. S.Tail(5) iii. S.Head(5) iv. S.tail()
11. Which of the following statement will import pandas library?
i. Import pandas as pd ii. import Pandas as py
iii. import pandas as pd iv. import panda as pd
22. Write a program to create a series object using a dictionary that stores the number of students in each house
of class 12D of your school.
Note: Assume four house names are Beas, Chenab, Ravi and Satluj having 18, 2, 20, 18 students respectively and
pandas library has been imported as pd.
24. What will be the output of the following code:
>>>import pandas as pd
>>>A=pd.Series(data=[35,45,55,40])
>>>print(A>45)
CBSE SP::2022.23:: PYTHON::Answers
10. iv. S.tail()
11. iii. import pandas as pd
22. St={‘Beas’ :18, ‘Chenab’ :20 , ‘ Ravi’ :20, ‘Satluj’ :18}
S1=pd.Series(St)
24.
10. CBSE COMPARTMENT::2021.22
No Questions from Series Topic
11. CBSE BOARD PAPER::2021.22
1. Which of the following statement is wrong?
(a) Can’t change the index of the Series
(b) We can easily convert the list, tuple and dictionary into a series
(c) A Series represents a single column in memory
(d) We can create empty Series
2. What type of error is returned by the following statement?
import pandas as pa
pa.Series([1,2,3,4], index=[‘a’,’b’,’c’])
a) Value Error b) Syntax Error c) Name Error d) Logical Error
3. Which is incorrect statement for the python
package Numpy?
a) It is a general purpose array processing package.
b) Numpy arrays are faster and more compact
c) It is multi-dimensional arrays
d) It is proprietary software
4. The data of any CSV file can be shown in
which of the following software?
a) MS Word b) Notepad c) Spreadsheet d) All of the above
5. Which python library is not used for data science?
a) Panda b) Numpy c) Matplotlib d) Tkinter
7. Consider the following code:
import numpy as np
import pandas as pd
L=np.array([10,20])
x=pd.Series( _________ ) # statement 1
print(x)
output of the above code is :
XII – IP (2025.2026 Material & Old CBSE Questions) 37 1. Series
0 1000
1 8000
dtype:int64
What is the correct statement for the above output in the following statement 1?
a) d=L*3 b) data=L**3 c) L*3 d) [10,20]**3
23. Which attribute is used with Series to count the total number of NaN values (non NaN values)
a) size b) len c) count d)count total
24. Consider the following Series in Python:
data=pd.Series([10,15,20,25,30,35],
index=[‘a’,’b’,’c’,’d’,’e’,’f’])
Which statement will display all odd values
(a) print(data%2= =0) (b) print(data(data%2!=0)
(c) print(data mod 2!=0) (d) print(data[data%3=0])
26. What will be the output of the following code?
import pandas as pd
import numpy
s=pd.Series(data=[31,54,34,89,12,23], dtype=numpy.int)
print(s>50)
(a) (b) (c) (d)
0 False 1 54 0 31 1 True
1 True 3 89 1 54 3 True
2 False dtype:int64. 2 34 dtype:bool
3 True 3 89
4 False 4 12
5 False 5 23
dtype:bool dtype:int64
33. Consider the following series
ser=pd.Series([‘C’,’O’,’M’,’F’,’O’,’R’,’T’,’A’,’B’, ‘L’,’E’], index=[1,2,3,4,5,6,7,8,9,10,11])
print(ser[4: ])
(a) (b) (c) (d)
4 F 4 F 4 F 5 O
5 O 5 O 5 O 6 R
6 R 6 R 6 R 7 T
7 T 7 T 7 T 8 A
8 A 8 A 8 A 9 B
9 B dtype:object 9 B 10 L
10 L dtype:object 11 E
11 E dtype:object
dtype:object
43. Consider the following code:
import pandas as pd
S1=pd.Series([23,24,35,56],index=[‘a’,’b’,’c’,’d’])
S2=pd.Series([27,12,14,15],index=[‘b’,’y’,’c’,’ab’])
df=pd.DataFrame(S1+S2)
print(df)
Output for the above code will be:
(a) (b) (c) (d)
0 0 0 0
a NaN a 50 b 50 a NaN
ab NaN b 36 y 36 ab NaN
b 51.0 c 49 c 49 b NaN
c 49.0 d 71 ab 71 c NaN
d NaN d NaN
y NaN y NaN
CBSE QP::2021.22:: PYTHON(T1)::Answers
XII – IP (2025.2026 Material & Old CBSE Questions) 38 1. Series
1.a 2.a 3.d 4.d 5.d 7.b
23a 24d 26a 33d 43a
12. CBSE SAMPLE PAPER :: 2021.22
1. The name “Pandas” is derived from the term:
a. Panel Data b. Panel Series c. Python Document d. Panel Data Frame
2. The command to install the pandas is:
a. install pip pandas b. install pandas c. pip pandas d. pip install pandas
3. Python pandas was developed by:
a. Guido van Rossum b. Travis Oliphant c. Wes McKinney d. Brendan Eich
4. Pandas Series is:
a. 2 Dimensional b. 3 Dimensional c. 1 Dimensional d. Multidimensional
5. Pandas is a:
a. Package b. Language c. Library d. Software
6. We can analyse the data in pandas with
a. Series b. Data Frame c. Both of the above d. None of the above
14. Which of the following import statement is not correct?
a. import pandas as class12 b. import pandas as 1pd
c. import pandas as pd1 d. import pandas as pd
26. What will be the output of the given code?
import pandas as pd
s = pd.Series([1,2,3,4,5], index=['akram',
'brijesh','charu','deepika','era'])
print(s['charu'])
a. 1 b. 2 c. 3 d. 4
27. Assuming the given series, named stud, which
command will be used to print 5 as output?
Amit 90
Ramesh 100
Mahesh 50
john 67
Abdul 89
Name: Student, dtype: int64
a. stud.index b. stud.length c. stud.values d. stud.size
28. A social science teacher wants to use a pandas series to teach about Indian historical monuments and its states. The
series should have the monument names as values and state names as indexes which are stored in the given lists, as
shown in the code. Choose the statement which will create the series:
import pandas as pd
Monument=['QutubMinar','Gateway of India', 'Red Fort','Taj Mahal']
State=['Delhi','Maharashtra','Delhi', 'Uttar Pradesh']
a. S=df.Series(Monument,index=State) b. S=pd.Series(State,Monument)
c. S=pd.Series(Monument,index=State) d. S=pd.series(Monument,index=State)
35. Consider the following series named animal:
L Lion
B Bear
E Elephant
T Tiger
W Wolf
dtype:object
Write the output of the command: print(animal[::-3])
a. L Lion
T Tiger
dtype:object
b. B Bear
XII – IP (2025.2026 Material & Old CBSE Questions) 39 1. Series
E Elephant
dtype:object
c. W Wolf
B Bear
dtype:object
d. W Wolf
T Tiger
dtype:object
40. Write the output of the given program:
import pandas as pd
S1=pd.Series([5,6,7,8,10], index=['v','w','x','y','z'])
l=[2,6,1,4,6]
S2=pd.Series(l,index=['z','y','a','w','v'])
print(S1-S2)
(a) (b) (c) (d)
a 0 a NaN v -1.0 a NaN
v -1.0 v -1.0 w 2.0 v -1.0
w 2.0 w 2.0 y 2.0 w 2.0
x NaN x NaN z 8.0 x 3.0
y 2.0 y 2.0 dtype: y 2.0
z 8.0 z 8.0 float64 z 8.0
dtype: dtype: dtype:
float64 float64 float64
43. Write the output of the given command:
import pandas as pd
s=pd.Series([1,2,3,4,5,6],index=['A','B','C','D','E','F'])
print(s[s%2= =0])
a. B 0
D 0
F 0
dtype: int64
b. A 1
B 2
C 5
dtype: int64
c. B 2
D 4
F 6
dtype: int64
d. B 1
D 2
F 3
dtype: int64
49. Read the statements given below. Identify the right option from the following for Attribute and method/function.
Statement A: Attribute always ends without parenthesis.
Statement B: Function/Method cannot work without arguments.
a. Both statements are correct.
b. Both statements are incorrect.
c. Statement A is correct, but Statement B is incorrect
d. Statement A is incorrect, but Statement B is correct
CBSE SP::2021.22:: PYTHON(T1)::Answers
1. a. Panel Data
2. d. pip install pandas
XII – IP (2025.2026 Material & Old CBSE Questions) 40 1. Series
3. c. Wes McKinney
4. c. 1 Dimensional
5. c. Library
6. c. Both of the above
14. b. import pandas as 1pd
26. c. 3
27. d. stud.size
28. c. S=pd.Series(Monument,index=State)
35. c
40. b
43. c
49. c. Statement A is correct, but Statement B is incorrect
13.CBSE COMPARTMENT 2021
4. What will be the output of the following program ?
import pandas as pd
x=6
S1=pd.Series(x,index=[1,2,4,6,8,9])
print(S1)
(A) 1 6
2 6
4 6
6 6
8 6
9 6
dtype: int64
(B) 0 6
dtype: int64
(C) 1 2 4 6 8 9
6 6 6 6 6 6
dtype: int64
(D) None of the above
5. Which one of the following is an attribute of the series in Pandas to set the index label for the given object ?
(A) label (B) index (C) loc (D) All of the above
24. Write a program in Python to create the series of all the alphabets of ''Happy'' with default index. Print the first three
alphabets.
27. Consider the following two series ‘A’ and ‘B’ :
A=pd.Series([2,4,6], index=[0,1,2])
B=pd.Series([1,3,5], index=[1,2,3])
(i) Write the statement to add both the series ‘A’ and ‘B’
(ii) Write the statement to multiply two series ‘A’ and ‘B’
34) Create a series S1 with the values (2,3,1).
(a) print(S1**3) (b) print(S1*3)
CBSE COMPARTMENT ::2021::ANSWERS
4. (A) 1 6
2 6
4 6
6 6
8 6
9 6
dtype: int64
5. (B) index
24. import pandas as pd
S=pd.Series(list('Happy'))
print(S.head(3))
27.i) A + B OR
A.add(B) OR
XII – IP (2025.2026 Material & Old CBSE Questions) 41 1. Series
B.add(A)
ii)
A*B OR
A.mul(B) OR
B.mul(A)
34) import pandas as pd
S1=pd.Series([2,3,1])
(a) 0 8
1 27
2 1
dtype: int64
(b) 0 6
1 9
2 3
dtype: int64
14.CBSE SAMPLE PAPER ::2020.21
4. Given a Pandas series called Sequences, the command which will display the first 4 rows is _______________.
a. print(Sequences.head(4)) b. print(Sequences.Head(4))
c. print(Sequences.heads(4) d. print(Sequences.Heads(4))
5. Given the following Series S1 and S2:
Write the command to find the sum of series S1 and S2.
(24) Consider a given Series , M1:
Write a program in Python Pandas to create the series.
(27) Consider the following Series object, S_amt
i) Write the command which will display the name of the furniture having rent>250.
ii) Write the command to name the series as Furniture.
34. Consider two objects x and y. x is a list whereas y is a Series. Both have values 20, 40, 90, 110.
What will be the output of the following two statements considering that the above objects have been created already.
a. print (x*2) b. print(y*2)
Justify your answer.
CBSE SP::2020.21:: PYTHON::Answers
4. print(Sequences.head(4))
5. print(S1+S2)
24. import pandas as pd
m1=pd.Series([45,65,24,89],S index=['term1','term2','term3','term4'])
27. i. print(S_amt[S_amt>250])
ii. S_amt.name= 'Furniture'
34. a. will give the output as: [20,40,90,110,20,40,90,110]
b. will give the output as
0 40
XII – IP (2025.2026 Material & Old CBSE Questions) 42 1. Series
1 80
2 180
3 220
Justification: In the first statement x represents a list so when a list is multiplied by a number, it is replicated that many
number of times.
The second y represents a series. When a series is multiplied by a value, then each element of the series is
multiplied by that number.
15.CBSE COMPARTMENT :: 2020
1.A) Find the output of following program:
import numpy as np
Profits=np.array([1520, 1245, 1345, 1525, 2110, 1020, 1725])
print(Profits[2:5])
1.B) Fill in the blank with appropriate numpy method to change the contents of the given 1 dimensional array Val1D
into a 2 dimensional array Val2D with 3 rows and 2 columns per row:
import numpy as np
Val1D=np.array([15,25,35,45,55,65])
Val2D = ____________________________
1.d) Write the output of the following Python code:
import numpy as np
Score1=np.array([90,92,94,96,95])
Score2=np.array([95,90,98,96,92])
S1=(np.where(Score1>Score2))
S2=(np.where(Score2>Score1))
print(Score1[S1], Score2[S2])
1.f) Write single line Pandas statements for each of the following.
(Assuming necessary modules have been imported):
(i) Declare a Pandas series named Packets having dataset as: [125, 92, 104, 92, 85, 116, 87, 90]
(ii) Display the median of the elements present in the dataset of Packets using the Pandas method for it.
(Above question (ii) is out of Syllabus Now)
1.g) Write Numpy single line statement for each of the following from (i) to (iii)
(i) To create a 3 x 2 array named ARR2D with the following values. (Assuming necessary modules have been imported
as np ):
(ii) Assign the contents of the above array ARR2D to a new 1D array named ARR1D.
(iii) Display content of array ARR1D as follows: [10 20 30 40 50 60]
(OR)
Write Numpy single line statement for each of the following from (i) to (iii)
(i) To create a 4 x 3 array named ARR with the following values. (Assuming necessary modules have been imported as
np ):
(ii) Topple the contents of the array ARR upside down so that its contents become:
(iii) Display the changed content of the array ARR in the following format :
XII – IP (2025.2026 Material & Old CBSE Questions) 43 1. Series
[ [100 110 120 ]
[ 70 80 90 ]
[ 40 50 60 ]
[ 10 20 30 ] ]
CBSE COMPARTMENT ::2020::ANSWERS
1 .a) [ 1345 1525 2110 ]
b) np.array(Val1D.reshape(3,2))
d) [92 95] [95 98]
f) (i) Packets = pd.Series([125, 92, 104, 92, 85,
116, 87, 90])
(ii) print(Packets.median())
1.g)
(i) ARR2D = np.array(([10, 20], [30, 40], [50,60]))
(ii) ARR1D = ARR2D.reshape(6)
(iii) print(ARR1D)
(OR)
(i) ARR = np.array(([10,20,30],[40,50,60], [70,80,90], [100,110,120]))
(ii) ARR=ARR[::-1]
(iii) print(ARR)
16.CBSE SAMPLE PAPER :: 2019.20
1.a) Find the output of following program:
import numpy as np
d=np.array([10,20,30,40,50,60,70])
print(d[-4])
1.b) Fill in the blank with appropriate numpy method to calculate or the covariance of an array
import numpy as np
data=np.array([1,2,3,4,5,6])
print(np._____(data,ddof=0))
(Above question 1(b) is out of Syllabus Now)
1.d) Write the output of the following code :
import numpy as np
array1=np.array([10,12,14,16,18,20,22])
print(array1[1:5:2])
1.f) What is series? Explain with the help of an example.
1.g) Write a code in Python to search for a given value in a list of elements(Without using in-built function)
Example:
If the List contains: [20,30,40,50,60,80,120]
and the element to be searched is:60
Then the output should be: Found at position 4
OR
Write a code in python to find the minimum value in a list.
Example:
If the List contains: [100,150,90,65,180,200]
Then the output should be: Minimum Value is 65
CBSE SP::2019..20:: PYTHON::Answers
1.a) [40 50 60 70]
1.b) print(np.cov(data,ddof=0))
1.d) [12 16]
1.f) Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float,
python objects, etc.).
The axis labels are collectively called index.
Example:
import pandas as pd
data =pd.Series([1,2,3,4,5]) # simple array
print(data)
XII – IP (2025.2026 Material & Old CBSE Questions) 44 1. Series
1.g)
List=[20,30,40,60,80,120]
Flag=0
No=int(input(“Enter a value”))
pos=0
for i in List:
if no==i:
print(“Found at position=”, pos+1)
Flag=1
break
pos=pos+1
if Flag= =0:
print(“value not found”)
OR
List=[100,150,90,65,180,200]
min=List[0]
for i in List:
if i<min:
min=i
print(“Minimum Value is”, min)
CBSE – QUESTION BANK QUESTIONS
Q.6. Answer the following based on the series given below.
import pandas as pd
list1=[1,2,3,4,5,6,7,8]
list2=['swimming','tt','skating','kho kho', 'bb', 'chess', 'football',"cricket"]
school=pd.Series(list1,index=list2)
school.name=("little")
print (school*2) #statement 1
print (school.tail(3)) # statement 2
print (school["tt"]) # statement 3
print (school[2:4]) # statement 4
i. Choose the correct name of the series object given above.
a) list1 b) list2 c) school d) little
ii. Choose the correct output for the statement:
print (school.tail(3)) # statement 2
a. swimming 1
tt 2
skating 3
b. chess 6
football 7
cricket 8
c. 4
d. kho kho 4
bb 5
chess 6
football 7
cricket 8
iii. Choose the correct output for the statement:
print (school["tt"]). # statement 3
a. 2 b. 3 c. tt 2 d. true
iv. Identify the correct output for:
print (school[2:4]) # statement 4.
XII – IP (2025.2026 Material & Old CBSE Questions) 45 1. Series
a. skating 3
kho kho 4
b. tt 2
skating 3
kho kho 4
c. skating 3
kho kho 4
bb 5
d. skating 3
kho kho 4
bb 5
chess 6
football 7
cricket 8
v. The correct output of the statetment:
print (school*2) # statement 1 will be .
a. swimming 3
tt 4
skating 5
kho kho 6
bb 7
chess 8
football 9
cricket 10
b. swimming 2
tt 4
skating 6
kho kho 8
bb 10
chess 12
football 14
cricket 16
c. swimming False
tt False
skating True
kho kho True
bb True
chess True
football True
cricket True
d. swimming 1
tt 4
skating 9
kho kho 16
bb 25
chess 36
football 49
cricket 64
ANSWERS
i. d) little ii. b) iii. a) 2 iv. a) v. b)
Q.11. Pushp, a student of class-XII, has been assigned a code to create a pandaseries S1, as shown below.
a 100
b 200
c 300
d 400
e 500
dtype: int64
XII – IP (2025.2026 Material & Old CBSE Questions) 46 1. Series
With reference to the above answer given questions:
i. Choose the command that will give the following output:
b 200
c 300
dtype: int64
a. print(S1[:3]) b. print(S1[0:3]) c. print(S1[1:3]) d. print(S1[2:4])
ii. Help him to identify the correct statement that can be used to extract t h e value with the index 'c'
a. print(S1[c]) b. print(S1(c)) c. print('S1' ['c']) d. print(S1 ['c'])
iii. Which of the following command will give the following output:
b 200
d 400
dtype: int64
a. print(S1.iloc[1:4]) b. print(S1.iloc[2:4]) c. print(S1.iloc(1:4)) d. print(S1.iloc[1:4:2])
iv. Which of the following command will display the series by adding 10 in eachvalue.
a. print(S1 [+10]) b. print(S1+10) c. print(S1)+10 d. print(S1)+print(10)
v. Pushp wants to delete the value against index 'd'. Help him to choose the suitable option to do so:
a. S1=S1.drop(d) b. S1=S1.drop('d') c. S1=drop('d') d. S1=S1.drop['d']
Solution:
i. c) print(s1[1:3]) ii. d) print(S1 ['c']) iii. d) print(S1.iloc[1:4:2])
iv. b) print(S1+10) v. b) S1=S1.drop('d')
Outputs
List and Tuples - Replication
Creation of Series with List/Tuple multiplication - Replication
ND Array and Series – Multiplication of corresponding values
1. Find the output of the following code:
import pandas as pd
lst1=[20,35,40]
ser1=pd.Series([20,35,40])
print(lst1+lst1) # Addition of two lists - Replication
print(ser1+ser1) #Addition of two Series–Adding Corr. elements
Ans. [20, 35, 40, 20, 35, 40]
0 40
1 70
2 80
2. Predict the output of the given Python code:
import pandas as pd
list1=[-10,-20,-30]
ser = pd.Series(list1*2) # Creating of Series with List multiplication - Replication
print(ser)
Ans.
0 -10 -20
2 -30
3 -10
4 -20
5 -30
3. What will be the output of the following code ?
import pandas as pd
S1=pd.Series(data=[1,7])
S2=pd.Series(S1+S1) # Adding 2 Series – Addition of Corr. values
print(S2)
Ans:
XII – IP (2025.2026 Material & Old CBSE Questions) 47 1. Series
0 2
1 14
4. What will be the output of the following code:
import pandas as pd
s1=pd.Series(data=2*(3,10))
print(s1) # Creating of Series with Tuple multiplication - Replication
Ans:
0 3
1 10
2 3
3 10
5) Create a series S1 with the values (2,3,1).
(a) print(S1**3) (b) print(S1*3)
(Applied on Correponding values)
Ans: import pandas as pd
S1=pd.Series([2,3,1])
(a) 0 8
1 27
2 1
dtype: int64
(b) 0 6
1 9
2 3
dtype: int64
6) Write the output of the following program
import pandas as pd
import numpy as np
n=np.arange(2,10,2)
print(n)
print(n*3) # ndarray - Applied on Correponding values
Ans: [2 4 6 8]
[ 6 12 18 24]
Assertion & Reasoning Questions
Assertion (A) : Pandas is an open-source Python library that offers high-performance, easy-to-use data structures and
data analysis tools.
Reason (R) : Professionals and developers are using the pandas library in data science and machine learning.
Ans.: a) Both A and R are True and R is correct explanation of A.
NCERT MATERIAL
NCERT SUMMARY:
❖ NumPy, Pandas and Matplotlib are Python libraries for scientific and analytical use.
❖ pip install pandas is the command to install Pandas library.
❖ A data structure is a collection of data values and the operations that can be applied to that data. It enables efficient
storage, retrieval and modification to the data.
❖ Two main data structures in Pandas library are Series and DataFrame. To use these data structures, we first need to
import the Pandas library.
❖ A Series is a one-dimensional array containing a sequence of values. Each value has a data label associated with it
also called its index.
❖ The two common ways of accessing the elements of a series are Indexing and Slicing.
❖ There are two types of indexes: positional index and labelled index. Positional index takes an integer value that
corresponds to its position in the series starting from 0, whereas labelled index takes any user-defined label as index.
XII – IP (2025.2026 Material & Old CBSE Questions) 48 1. Series
❖ When positional indices are used for slicing, the value at end index position is excluded, i.e., only (end - start)
number of data values of the series are extracted. However with labelled indexes the value at the end index label is
also included in the output.
❖ All basic mathematical operations can be performed on Series either by using the operator or by using appropriate
methods of the Series object.
❖ While performing mathematical operations index matching is implemented and if no matching indexes are found
during alignment, Pandas returns NaN so that the operation does not fail.
NCERT EXERSIZE
1. What is a Series and how is it different from a 1-D array, a list and a dictionary?
5. Create the following Series and do the specified operations:
a) EngAlph, having 26 elements with the alphabets as values and default index values.
b) Vowels, having 5 elements with index labels ‘a’, ‘e’, ‘i’, ‘o’ and ‘u’ and all the five values set to zero.
Check if it is an empty series.
c) Friends, from a dictionary having roll numbers of five of your friends as data and their first name as keys.
d) MTseries, an empty Series. Check if it is an empty series.
e) MonthDays, from a numpy array having the number of days in the 12 months of a year. The labels should be the
month numbers from 1 to 12.
6. Using the Series created in Question 5, write commands for the following:
a) Set all the values of Vowels to 10 and display the Series.
b) Divide all values of Vowels by 2 and display the Series.
c) Create another series Vowels1 having 5 elements with index labels ‘a’, ‘e’, ‘i’, ‘o’ and ‘u’ having
values [2,5,6,3,8] respectively.
d) Add Vowels and Vowels1 and assign the result to Vowels3.
e) Subtract, Multiply and Divide Vowels by Vowels1.
f) Alter the labels of Vowels1 to [‘A’, ‘E’, ‘I’, ‘O’, ‘U’].
7. Using the Series created in Question 5, write commands for the following:
a) Find the dimensions, size and values of the Series EngAlph, Vowels, Friends, MTseries, MonthDays.
b) Rename the Series MTseries as SeriesEmpty.
c) Name the index of the Series MonthDays as monthno and that of Series Friends as Fname.
d) Display the 3rd and 2nd value of the Series Notes Friends, in that order.
e) Display the alphabets ‘e’ to ‘p’ from the Series EngAlph.
f) Display the first 10 values in the Series EngAlph.
g) Display the last 10 values in the Series EngAlph.
h) Display the MTseries.
8. Using the Series created in Question 5, write commands for the following:
a) Display the names of the months 3 through 7 from the Series MonthDays.
b) Display the Series MonthDays in reverse order.
ACTIVITY
2.1 Create a series having names of any five famous monuments of India and assign their States as index values.
2.2 Write the statement to get NewDelhi as output using positional index.
>>> seriesCapCntry = pd.Series(['NewDelhi',
'WashingtonDC', 'London', 'Paris'],
index=['India', 'USA', 'UK', 'France'])
>>> seriesCapCntry['India']
'NewDelhi'
2.3 Consider the following code:
>>>import pandas as pd
>>>import numpy as np
>>>s2=pd.Series([12,np.nan,10])
>>>print(s2)
Find output of the above code and write a Python statement to count and display only non null values in the above
series.
2.4 Draw two tables for subtraction similar to tables 2.2 and 2.3 showing the changes in the series elements and
corresponding output without replacing the missing values, and after replacing the missing values with 1000.
seriesA = pd.Series([1,2,3,4,5], index =['a', 'b', 'c', 'd', 'e'])
seriesB = pd.Series([10,20,-10,-50,100], index = ['z', 'y', 'a', 'c', 'e'])
XII – IP (2025.2026 Material & Old CBSE Questions) 49 1. Series
>>> seriesA + seriesB
>>> seriesA.add(seriesB, fill_value=0)
2.5 Draw two tables for multiplication similar to Tables 2.2 and 2.3 showing the changes in the series elements and
corresponding output without replacing the missing values, and after replacing the missing values with 0.
2.6 Draw two tables for division similar to tables 2.2 and 2.3 showing the changes in the series elements and
corresponding output without replacing the missing values, and after replacing the missing values with 0.
Think and Reflect:
While importing Pandas, is it mandatory to always use pd as an alias name? What would happen if we give any other
name?
XII – IP (2025.2026 Material & Old CBSE Questions) 50 1. Series
DATA FRAMES
Syllabus:
Data Frames: Creation - from dictionary of Series, list of dictionaries, Text/CSV files; display; iteration;
Operations on rows and columns: add, select, delete, rename; Head and Tail functions; Indexing using Labels,
Boolean Indexing; ******************
A DataFrame is a two-dimensional labelled data structure like a table of MySQL. It contains rows and
columns, and therefore has both a row and column index.
Each column can have a different type of value such as numeric, string, boolean, etc., as in tables of a
database.
Characteristics:
● It has two indexes/axes.
● Row index (axis=0) & Column index (axis=1).
● Row index is known as index,
● Column index is known as column name.
● Indexes can be of numbers or letters or strings.
● Different columns can have data of different types.
● Value is mutable (ie its value can change)
● We can add/delete rows/columns in a DataFrame ie size-mutable.
Example
CREATING A DATAFRAME
Before creation, we need to import two modules.
import pandas (or) import pandas as pd
import numpy (or) import numpy as np
Note: Numpy is required whenever we use numpy arrays only. In the place of pd or np, we can use any valid identifier.
Syntax:
<dataFrameObject>=pandas.DataFrame(<a 2D datastructure>, [columns=<column sequence>], [index=<index sequence>]).
We can create using:
● Lists
● Dictionary (Two-dimensional dictionaries ie dictionaries having lists or dictionaries or ndarrays or
Series objects, etc.)
● Two-dimensional ndarrays (NumPy array)
● Series type object
● Another DataFrame object
Displaying a DataFrame is same as the way we display other variables and objects.
(a) Creating an empty DataFrame:
Ex: import pandas as pd
df=pd.DataFrame()
print(df) Output
Empty DataFrame
Columns: [ ]
Index: [ ]
(b) From a Series:
Example 1: Creation of Dataframe using single series
import pandas as pd
series = pd.Series([10, 20, 30, 40], name='Data')
df = pd.DataFrame(series)
print(df)
XII – IP (2025.2026 Material & Old CBSE Questions) 51 2. DataFrames
Output
Data
0 10
1 20
2 30
3 40
Example 2: Creation of Dataframe using multiple series objects (Dictionary method)
pandas as pd
series1 = pd.Series([10, 20, 30, 40], name='Series1')
series2 = pd.Series([1, 2, 3, 4], name='Series2')
df = pd.DataFrame({'Series1': series1, 'Series2': series2})
print(df)
Output
Series1 Series2
0 10 1
1 20 2
2 30 3
3 40 4
Example 3: Creation of Dataframe using single multiple series objects (Dictionary method)
import pandas as pd
RN=pd.Series([11,12,13,14])
SN=pd.Series(['Rajesh','Likhith','Navya','Bhavya'])
M=pd.Series([56,75,91,82])
studict={'RNo':RN,'SName':SN,'Marks':M}
mydf=pd.DataFrame(studict)
print(mydf)
Output
Example 4 (Dictionary of Series):
import pandas as pd
RS={'Ravi': pd.Series([90, 91], index=[‘Maths’, ‘Science’]), ‘Kiran’: pd.Series([80, 81],index= [‘Maths’,’Science’]),
‘Chinna’: pd.Series([70, 71],index=[‘Maths’,’Science’])}
ResultDF = pd.DataFrame(RS)
print(ResultDF)
Output
Note: When a DataFrame is created from a Dictionary of Series, the resulting index or row labels are a union
of all series indexes used to create the DataFrame.
Program:
import pandas as pd
Dict = { 'Series1':pd.Series([1,2,3],index = ['a', 'b', 'c']) , 'Series2' :pd.Series([10,20,-10],index = ['a', 'c', 'e'])}
DF= pd.DataFrame(Dict)
print(DF)
Output
(c) Using a List:
Creating using a list having 1-D lists:
XII – IP (2025.2026 Material & Old CBSE Questions) 52 2. DataFrames
import pandas as pd
vowels=['a','e','i','o','u']
df=pd.DataFrame(vowels,index=[10,11,12,13,14], columns=['One'])
print(df)
Output
One
10 a
11 e
12 i
13 o
14 u
Creating using a list having List of lists:
import pandas as pd
data = [['Mohan', 10], ['Lakshmi', 12], ['Suresh', 13]]
df = pd.DataFrame(data,index=
['First','Second','Third'], columns=['Name', 'Age'])
print(df)
Output
Name Age
First Mohan 10
Second Lakshmi 12
Third Suresh 13
(d) Using ndarray:
We can pass a two-dimensional Numpy array (ie having shape as (<n>,<n>) to DataFrame( ) to create a
dataframe object.
import pandas as pd
import numpy as np
ndata=np.array([[11,12],[13,14],[15,16]])
df=pd.DataFrame(ndata,index=["Frow","Srow", "Trow"],columns=["Onec","Twoc"])
#df=pd.DataFrame(vowels,columns=['One'], index=[10,11,12,13,14])
print(df)
Output
Onec Twoc
Frow 11 12
Srow 13 14
Trow 15 16
Ex2: Program:
import numpy as np
import pandas as pd
narr=np.array([[10.7,20.5],[40,50],[25.2,55]])
mydf=pd.DataFrame(narr,columns=["One","Two"], index=['A','B','C'])
print(mydf)
Output
We can specify either columns or index or both the sequences.
Note : If, the rows of ndarrays differ in length, i.e., if number of elements in each row differ, then Python will
create just single column in the dataframe object and the type of the column will be considered as object.
Ex3: Program:
narr=np.array([[10.7,20.5,30.2],[40,50],[25,55,11,45]],
dtype="object")
mydf=pd.DataFrame(narr)
Output
XII – IP (2025.2026 Material & Old CBSE Questions) 53 2. DataFrames
Ex: 4 Program:
>>>import numpy as np
>>>array1 = np.array([10,20,30])
>>>array2 = np.array([100,200,300])
>>>array3 = np.array([-10,-20,-30, -40])
>>>DF1 = pd.DataFrame(array1)
>>>DF1
0
0 10
1 20
2 30
We can create a DataFrame using more than one ndarrays, as shown in the following example:
>>> DF2 = pd.DataFrame([array1, array3,
array2], columns=[ 'A', 'B', 'C', 'D'])
>>> dFrame5
A B C D
0 10 20 30 NaN
1 -10 -20 -30 -40.0
2 100 200 300 NaN
(e) Using Dictionaries:
Creating a DataFrame using Dictionary:
A 2-D dictionary is a dictionary having items as (key:value), where value part is a data structure of
any type i.e., another dictionary, an ndarray, a series object, a list, etc.
Value part of all the keys should have similar structure.
Creating a dataframe from a 2D dictionary having values as – lists (Dictionary of Lists):
import pandas as pd
dict={'RNo':[51,52,53,54],'SName':['Lahari', 'Chanakya', 'Harish','Neha'],'Marks':[55,62,52,75]}
df=pd.DataFrame(dict, index= ['First','Second','Third','Fourth'])
print(df)
Output
RNo SName Marks
First 51 Lahari 55
Second 52 Chanakya 62
Third 53 Harish 52
Fourth 54 Neha 75
Note: If the number of indexes does not match the index sequence, then “ValueError” will occur.
Example :Given a dictionary that stores “State names” as index, “Mother Tongue” &“Population” as column
names. Note: Population in crores.
Program:
import pandas as pd
dict={'Mother Tongue':['Telugu','Tamil','Hindi'], 'Population':[6,8,12]}
df=pd.DataFrame(dict,index=['AP','TN','Maharastra'])
print(df)
Creating a dataframe from a 2D dictionary having values as - dictionary object:
dict={'RNo':{'First':51,'Second':52,'Third':53,'Fourth':54}, 'SName':{'First':'Lahari','Second':'Chanakya',
'Third':'Harish', 'Fourth':'Neha'}, 'Marks':{'First':55,'Second':62,'Third':52, 'Fourth':75}}
df=pd.DataFrame(dict)
XII – IP (2025.2026 Material & Old CBSE Questions) 54 2. DataFrames
dict={'First':{'RNo':51,'SName':'Lahari','Marks':55}, 'Second':{'RNo':52,'SName':'Chanakya','Marks':62},
'Third':{'RNo':53,'SName':'Harish','Marks':52}, 'Fourth':{'RNo':54,'SName':'Neha','Marks':75}}
df=pd.DataFrame(dict)
Special Condition:
Two dictionaries with dissimilar keys as inner dictionaries of a 2D dictionary. For this DataFrame can be
created with non-matching inner keys.
All the inner keys become indexes, NaN values will be added for non-matching keys of inner dictionaries.
import pandas as pd
C1={'Qty':95,'Half Yearly':89}
C2={'Half Yearly':94,'Annual':97}
Marks={'Student 1':C1,'Student 2':C2}
df=pd.DataFrame(Marks)
print(df)
Output
Creating a Dataframe Object from a LIST OF DICTIONARIES:
If we pass a 2D list having dictionaries as its elements (list of dictionaries) to pandas.DataFrame()
function, it will create a DataFrame object such that the inner dictionary keys will become the columns and
inner dictionary’s values will make rows.
Ex1:
import pandas as pd
dict1={'RNo':51,'SName':'Lahari','Marks':55}
dict2={'RNo':52,'SName':'Chanakya','Marks':62}
dict3={'RNo':53,'SName':'Harish','Marks':52}
dict4={'RNo':54,'SName':'Neha','Marks':75}
students=[dict1,dict2,dict3,dict4]
df=pd.DataFrame(students)
print(df)
Note : We can also include indexes as follows:
df=pd.DataFrame(students,index=['First','Second', 'Third','Fourth'])
Note: If we do not give the same column name in every row, it will com “NaN” values.
import pandas as pd
dict1={'RNo':51,'SName':'Lahari','Marks':55}
dict2={'RNo':52,'Name':'Chanakya','Marks':62}
dict3={'RNo':53,'Name':'Harish','Marks':52}
dict4={'RNo':54,'SName':'Neha','Marks':75}
students=[dict1,dict2,dict3,dict4]
df=pd.DataFrame(students,index= ['First','Second','Third','Fourth'])
print(df)
XII – IP (2025.2026 Material & Old CBSE Questions) 55 2. DataFrames
Ex2: (List of Dictionaries)
>>> listDict = [{'a':10, 'b':20}, {'a':5, 'b':10,'c':20}]
>>> dFrameListDict = pd.DataFrame(listDict)
>>> dFrameListDict
a b c
0 10 20 NaN
1 5 10 20.0
Note: Here, the dictionary keys are taken as column labels, and the values corresponding to each key are taken as rows.
There will be as many rows as the number of dictionaries present in the list. In the above example there are two
dictionaries in the list. So, the DataFrame consists of two rows. Number of columns in a DataFrame is equal to the
maximum number of keys in any dictionary of the list. Hence, there are three columns as the second dictionary has
three elements. Also, note that NaN (Not a Number) is inserted if a corresponding value for a column is missing.
Inserting Rows & Column Names:
import pandas as pd
#each inner list is a row
lists=[[51,'Lahari',55],[52,'Chanakya',62],[53,'Harish',52]]
df=pd.DataFrame(lists,columns=['RNo','SName', 'Marks'],index=['First','Second','Third'])
print(df)
(f) From existing DataFrame:
Program:
import pandas as pd
dict={'RNo':[51,52,53,54],
'SName':['Lahari','Chanakya','Harish','Neha'],
'Marks':[55,62,52,75]}
df=pd.DataFrame(dict)
dfnew=pd.DataFrame(df)
print(dfnew)
Output
(new DataFrame created from existing DataFrame)
(f) From CSV file:
Full details can learn from 3rd chapter (CSV Files)
DISPLAY
Displaying a DataFrame is same as the way we display other variables and objects.
Example Program:
import pandas as pd
dict={'RNo':[51,52,53,54],
'SName':['Lahari','Mohan','Sudhir','Neha'],
'Marks':[95,72,85,55]}
df=pd.DataFrame(dict)
print(df)
XII – IP (2025.2026 Material & Old CBSE Questions) 56 2. DataFrames
ITERATION (Pandas 2 Chapter)
Iterating Over a Data Frame
Iterating Over a DataFrame:
>>> dict={'Teachers':[20,10],'Students':[200,150], 'Ratio':[10,15]}
>>>DF=pd.DataFrame(dict,index=['Private','Govt'])
iterrows( ) : This method iterates over dataframe row wise where each horizontal subset is in the form of
(row-index,Series) where Series contains all column values for that row-index.
Example Program: Using iterrows( ) to extract data from dataframe row wise.
import pandas as pd
dict={'Teachers':[20,10],'Students':[200,150],
'Ratio':[10,15]}
DF=pd.DataFrame(dict,index=['Private','Govt'])
for (row,rowSeries) in DF.iterrows():
print("Row index:",row)
print("Containing: ")
print(rowSeries)
OUTPUT
Row index: Private
Containing:
Teachers 20
Students 200
Ratio 10
Name: Private, dtype: int64
Row index: Govt
Containing:
Teachers 10
Students 150
Ratio 15
Name: Govt, dtype: int64
Example : Using iterrows( ) to extract row-wise Series objects
import pandas as pd
dict={'Teachers':[20,10],'Students':[200,150],
'Ratio':[10,15]}
DF=pd.DataFrame(dict,index=['Private','Govt'])
for (row,rowSeries) in DF.iterrows():
print("Row index:",row)
print("Containing: ")
i=0
for val in rowSeries:
print("At",i,"position: ",val)
i=i+1
OUTPUT
Row index: Private
Containing:
At 0 position: 20
At 1 position: 200
At 2 position: 10
Row index: Govt
Containing:
At 0 position: 10
At 1 position: 150
At 2 position: 15
XII – IP (2025.2026 Material & Old CBSE Questions) 57 2. DataFrames
Write a program to print the DataFrame DF, one row at a time
import pandas as pd
dict={'Teachers':[20,10],'Students':[200,150],
'Ratio':[10,15]}
DF=pd.DataFrame(dict,index=['Private','Govt'])
for i,j in DF.iterrows():
print(i)
print(j)
print("____________")
OUTPUT
Private
Teachers 20
Students 200
Ratio 10
Name: Private, dtype: int64
____________
Govt
Teachers 10
Students 150
Ratio 15
Name: Govt, dtype: int64
Putting Individual columns from a row:
When accessing rows of a DataFrame using iterrows(), then by using rowSeries[<column>], you can
print individual column value from that row ie.,after the line,for r, Row in df.iterrows( ):
You can print individual column value as :
Row[<column name>]
Write a program to print only the values from Teachers column, for each row
import pandas as pd
dict={'Teachers':[20,10],'Students':[200,150],
'Ratio':[10,15]}
DF=pd.DataFrame(dict,index=['Private','Govt'])
for row,rowSeries in DF.iterrows():
print(rowSeries['Teachers'])
print("------")
OUTPUT
20
------
10
------
iteritems( ): This method iterates over dataframe column wise where each vertical subset is in the form of
(col-index,Series) where Series contains all row values for that column-index.
Note: in present versions, iteritems( ) is replaced with items( )
Example : Using iteritems( ) to extract data from dataframe column wise.
import pandas as pd
dict={'Teachers':[20,10],'Students':[200,150],
'Ratio':[10,15]}
DF=pd.DataFrame(dict,index=['Private','Govt'])
for (col,colSeries) in DF.items(): # iteritems( )
print("Column index:",col)
print("Containing: ")
print(colSeries)
OUTPUT
Column index: Teachers
Containing:
XII – IP (2025.2026 Material & Old CBSE Questions) 58 2. DataFrames
Private 20
Govt 10
Name: Teachers, dtype: int64
Column index: Students
Containing:
Private 200
Govt 150
Name: Students, dtype: int64
Column index: Ratio
Containing:
Private 10
Govt 15
Name: Ratio, dtype: int64
Example : Using iteritems( ) to extract dataframe column wise series object
import pandas as pd
dict={'Teachers':[20,10],'Students':[200,150],
'Ratio':[10,15]}
DF=pd.DataFrame(dict,index=['Private','Govt'])
for (col,colSeries) in DF.items(): #iteritems( )
print("Column index:",col)
print("Containing: ")
i=0
for val in colSeries:
print("At row ",i,":",val)
i=i+1
OUTPUT
Column index: Teachers
Containing:
At row 0 : 20
At row 1 : 10
Column index: Students
Containing:
At row 0 : 200
At row 1 : 150
Column index: Ratio
Containing:
At row 0 : 10
At row 1 : 15
Write a program to print the DataFrame DF, one column at a time
import pandas as pd
dict={'Teachers':[20,10],'Students':[200,150],
'Ratio':[10,15]}
DF=pd.DataFrame(dict,index=['Private','Govt'])
for i,j in DF.items(): #iteritems( )
print(i)
print(j)
print("____________")
OUTPUT
Teachers
Private 20
Govt 10
Name: Teachers, dtype: int64
____________
Students
Private 200
Govt 150
Name: Students, dtype: int64
____________
Ratio
Private 10
Govt 15
Name: Ratio, dtype: int64
XII – IP (2025.2026 Material & Old CBSE Questions) 59 2. DataFrames
OPERATIONS ON ROWS & COLUMNS
add, select, delete, rename
SELECTING/ACCESSING DATA
&
ADDING DATA
import pandas as pd
dict={'Eng':[68,72,66],'Tel':[55,84,90],'Mat':[60,70,65],
'Soc':[80,90,85]}
df=pd.DataFrame(dict,index=['Raj','Pavan','Mohan'])
print(df)
Note: The process of adding and modifying rows/columns value is similar.
Selecting/Accessing a subset from a DataFrame using Row/Column Names using loc function:
To access row(s) and/or a combination of rows and columns, we can use loc function.
Syntax:
<DataFrame Object>.loc[<startrow>:<endrow>, <startcolumn>:<endcolumn>]
Note: With loc, Both start label and end label are included when given as start:end
Selecting/Accessing a subset from a DataFrame using Row/Column Names using iloc function:
With this function, we can extract, subset from dataframe using the row and column numeric
index/position. iloc means integer location.
Syntax:
<DF Object>.iloc[<start row index>:<end row index>, <start col index>:<end column index>]
Note: With iloc, like slices end index/position is excluded when given as start:end.
.at function: Access a single value for a row/column label pair by labels.
Syntax:<DF Object>.at[<row label>,<col label>]
.iat function: Access a single value for a row/column label pair by index position.
Syntax: <DF Object>.at[<row index no><col index no>]
SINGLE COLUMN
SELECTING/ACCESSING A SINGLE COLUMN:
Syntax:<DataFrame object> [<column name>] (or) <DataFrame object>.<column name>
>>>df['Eng']
Raj 68
Pavan 72
Mohan 66
Name: Eng, dtype: int64
>>>df.Eng
Raj 68
Pavan 72
Mohan 66
Name: Eng, dtype: int64
XII – IP (2025.2026 Material & Old CBSE Questions) 60 2. DataFrames
Adding/Modifying a column
Assigning a value to a column:
● Will modify it, if the column already exists
● Will add a new column, if it does not exist already.
Syntax:
<DF Object>.<column name>=<new value>
(or)<DF Object>[<column>]=<new value>
MODIFYING a Column:
Note: Assigning values to a new column label that does not exist will create a new column at the end. If the
column already exists in the DataFrame then the assignment statement will update the values of the already
existing column, for example:
df['Eng']=[40,50,60]
df['Tel']=55
df.Mat=70,80,90
df.Soc=100
Note : If we give following,
>>> df.corporate=11,12,13 or
>>> df.corporate=[11,12,13],
No error will be displayed, but nothing will be stored in DataFrame.
ADDING a Column:
>>>df['Hin']=[89,78,76]
SELECTING/ACCESSING a column (loc):
>>>df.loc[:,'Eng']
Raj 68
Pavan 72
Mohan 66
Name: Eng, dtype: int64
MODIFYING a Column (loc):
>>>df.loc[:,'Eng']=[10,20,30]
# df.loc[:,'Eng']=10,20,30
>>>df.loc[:,'Mat']=100
ADDING a Column (loc):
>>>df.loc[:,'IP']=[10,20,30]
XII – IP (2025.2026 Material & Old CBSE Questions) 61 2. DataFrames
>>>df.loc[:,'Hin']=50
SELECTING/ACCESSING a column (iloc):
>>>df.iloc[:,1]
Raj 55
Pavan 84
Mohan 90
Name: Tel, dtype: int64
>>>df.iloc[:,[1]]
Tel
Raj 55
Pavan 84
Mohan 90
MODIFYING a Column (iloc):
>>>df.iloc[:,1]=[40,50,60]
>>>df.iloc[:,3]=70
Note: We cannot add a Column using iloc.
If you try to add new column using iloc, “IndexError” will come.
Ex: >>>df.iloc[:,4]=95
IndexError : iloc cannot enlarge its target object
>>> df.iloc[:,1:3]=[[1,2],[3,4],[5,6]]
MULTIPLE COLUMNS
SELECTING/ACCESSING multiple column:
<DataFrame object>[ [<column name>, <column name>,…..] ]
>>>df[['Tel','Soc','Mat']]
MODIFYING multiple Columns values:
XII – IP (2025.2026 Material & Old CBSE Questions) 62 2. DataFrames
>>>df[['Tel','Soc','Mat']]=10,20,30 # df[['Tel','Soc','Mat']]=[10,20,30]
>>> df[['Tel','Soc','Mat']]=[[1,2,3],[4,5,6],[7,8,9]]
SELECTING/ACCESSING multiple columns (loc):
>>> df.loc[:,'Eng':'Mat']
Note: All columns between start and end columns are listed.
>>> df.loc[:,'Tel':]
>>>df.loc[:,'Mat':'Eng']
Empty DataFrame
Columns: []
Index: [Raj, Pavan, Mohan]
>>>df.loc[:,['Soc','Tel','Eng']]
[[[
MODIFYING multiple Columns values (loc):
>>>df.loc[:,'Eng':'Mat']=50,60,70
>>>df.loc[:,['Soc','Tel','Eng']]=10,20,30
SELECTING/ACCESSING multiple columns (iloc):
>>> df.iloc[:,1:3] #Excluding column 3
>>> df.iloc[:,[2,0]]
>>> df.iloc[:,1:]
XII – IP (2025.2026 Material & Old CBSE Questions) 63 2. DataFrames
>>> df.iloc[:,2:0]
Empty DataFrame
Columns: []
Index: [Raj, Pavan, Mohan]
>>> df.iloc[:,[2,0,1]]
MODIFYING multiple Columns values (iloc):
>>>df.iloc[:,1:3]=[25,35]
SINGLE ROW
SELECTING/ACCESSING one row (loc):
Just give the row name/label.
>>>df.loc['Pavan']
# df.loc['Pavan',] or df.loc['Pavan',:]
Eng 72
Tel 84
Mat 70
Soc 90
Name: Pavan, dtype: int64
>>> df.loc['Kiran']
KeyError: 'Kiran'
MODIFYING one row (loc):
>>>df.loc["Raj"]=91,92,93,94
#df.loc[“Raj”,:] = [91,92,93,94]
>>>df.loc["Pavan"]=100
>>> df.loc['Mohan',:]=601,602,603
ValueError: could not broadcast input array from shape (3,) into shape (4,)
ADDING one row (loc):
>>>df.loc['Kumar']=91,92,93,94
Note: If we try to add a row with lesser values than the number of columns in the DataFrame, it results in
a ValueError, with the error message: ValueError: Cannot set a row with mismatched columns.
Similarly, if we try to add a column with lesser values than the number of rows in the DataFrame, it results
in a ValueError, with the error message: ValueError: Length of values does not match length of index.
SELECTING/ACCESSING one row (iloc):
XII – IP (2025.2026 Material & Old CBSE Questions) 64 2. DataFrames
>>>df.iloc[1] #df.iloc[1,] or df.iloc[1,:]
Eng 72
Tel 84
Mat 70
Soc 90
Name: Pavan, dtype: int64
>>> df.iloc[4]
IndexError: single positional indexer is out-of-bounds
MODIFYING one row (iloc):
>>>df.iloc[2]=75
>>>df.iloc[1]=81,82,83,84
# df.iloc[1]=[81,82,83,84]
# df.iloc[1,:]=[81,82,83,84]
Note: We cannot add a row using iloc.
If you try to add new column using iloc, “IndexError” will come.
Ex:
>>>df.iloc[:,3]=91,92,93,94
IndexError : iloc cannot enlarge its target object
>>> df.iloc[[2,0]]=[[100,200,300,400],[11,22,33,44]]
MULTIPLE ROWS
SELECTING/ACCESSING multiple rows (loc):
>>>df.loc['Raj':'Mohan']
# df.loc['Raj':'Mohan', ] or df.loc['Raj':'Mohan', :]
>>>df.loc['Pavan':'Mohan']
>>>df.loc[['Mohan','Raj']]
>>>df.loc['Pavan':'Raj']
Empty DataFrame
Columns: [Eng, Tel, Mat, Soc]
Index: [ ]
MODIFYING multiple rows (loc):
>>> df.loc[['Mohan','Raj']]=[[1,2,3,4],[5,6,7,8]]
XII – IP (2025.2026 Material & Old CBSE Questions) 65 2. DataFrames
SELECTING/ACCESSING multiple rows (iloc):
>>> df.iloc[0:3] # df.iloc[0:3,] or df.iloc[0:3,:]
>>>df.iloc[0:2]
>>>df.iloc[1:10]
>>>df.iloc[1:1]
Empty DataFrame
Columns: [Eng, Tel, Mat, Soc]
Index: [ ]
>>>df.iloc[[2,1]] #df.iloc[[2,1], ] or df.iloc[[2,1], : ]
MODIFYING multiple rows (iloc):
>>>df.iloc[0:2]=[[1,2,3,4],[5,6,7,8]]
Modifying All Rows (iloc):
>>>df[ : ]
>>>df[ : ] = 10
RANGE OF COLUMNS
FROM A RANGE OF ROWS
SELECTING/ACCESSING range of columns from a range of rows (loc):
<DF Object>.loc[<startrow>:<endrow>, <startcolumn>:<endcolumn>]
>>> df.loc['Pavan':'Mohan','Tel':'Soc']
>>>df.loc['Mohan':'Raj','Eng':'Soc']
Empty DataFrame
Columns: [Eng, Tel, Mat, Soc]
Index: [ ]
>>>df.loc['Raj':'Pavan','Mat':'Eng']
Empty DataFrame
Columns: [ ]
XII – IP (2025.2026 Material & Old CBSE Questions) 66 2. DataFrames
Index: [Raj, Pavan]
MODIFYING range of columns from a range of rows (loc):
>>>df.loc['Pavan':'Mohan','Tel':'Soc']=[[1,2,3],[4,5,6]]
SELECTING/ACCESSING range of columns from a range of rows (iloc):
>>> df.iloc[1:3,0:2] #Rows 1,2 & Columns 0,1
>>>df.iloc[[1,2],[2,0,1]]
>>> df.iloc[2:2,0:2]
Empty DataFrame
Columns: [Eng, Tel]
Index: []
>>> df.iloc[1:3,2:0]
Empty DataFrame
Columns: []
Index: [Pavan, Mohan]
>>> df.iloc[[1,3],0:2]
IndexError: positional indexers are out-of-bounds
MODIFYING range of columns from a range of rows (iloc):
>>>df.iloc[0:2,1:4]=[[21,22,23],[31,32,33]]
SINGLE VALUE
SELECTING/ACCESSING a single value:
Either give name of row or numeric index in square brackets.
Syntax:<DF Object>.<column>
[<row name or row numeric index>]
Ex: >>df.Eng['Pavan']
72
MODIFYING a single value:
>>>df.Eng['Pavan']=200 will change the value to 200
XII – IP (2025.2026 Material & Old CBSE Questions) 67 2. DataFrames
>>> df.Tel[0]=500
SELECTING/ACCESSING a single value (loc):
>>>df.loc['Pavan','Mat']
100
MODIFYING a single value (loc):
Specify the row label and the column name, then assign the new value.
>>>df.loc['Pavan','Mat']=100
SELECTING/ACCESSING a single value (iloc):
>>>df.iloc[2,3]
85
MODIFYING a single value (iloc):
>>>df.iloc[2,3]=500
.at function: Access a single value for a row/column label pair by labels.
Syntax:<DF Object>.at[<row label>,<col label>]
Ex:
>>> df.at['Raj','Mat']
60
>>> df.at['Raj','Mat']=150 will change the value to 150
>>> df.at['Kiran','Soc']
KeyError: 'Kiran'
>>> df.at['Raj','IP']
KeyError: 'IP'
.iat function: Access a single value for a row/column label pair by index position.
Syntax:
<DF Object>.at[<row index no><col index no>]
XII – IP (2025.2026 Material & Old CBSE Questions) 68 2. DataFrames
>>> df.iat[2,2]
65
# df.iat[2,3]=30 will change the value to 30
ASSIGN FUNCTION
<DF object>=<DF object>.assign(<column name>=<values for column>)
>>> df=df.assign(Mat=[10,11,12])
>>>df=df.assign(IP=[81,82,83])
>>>df=df.assign(Tel=77)
>>>df=df.assign(New=[55,56])
ValueError: Length of values (2) does not match length of index (4)
RENAMING ROWS/COLUMNS
To change the name of any row/column individually, we can use the rename( ) function.
rename( ) function by default does not make changes in the original dataframe. It creates a new
dataframe with the changes and the original dataframe remains unchanged.
Syntax:
<DF>.rename(index={<names dictionary>},
columns={<names dictionary>}, inplace=False)
Renaming Row Indexes:
>>>df.rename(index={'Raj':'Mr.Rajesh','Mohan':'Mohan Garu'},inplace=True)
Renaming Column Indexes (Column Labels):
>>> df.rename(columns={'Eng':'English', 'Mat':'Maths'},inplace=True)
Another Example:
dict={'RNo':[51,52,53],'SName':['Suresh','Naresh','Bhavesh']}
df=pd.DataFrame(dict, index=['First','Second','Third'])
>>>df.rename(index={'Second':'Two'}, columns={'RNo':'RollNo'},inplace=True)
Note : If we do not add “inplace=True”, when we are executing the commands only, it will show the modified
values. But really it won’t modifies the values. So to modify values we need to add “inplace=True”.
XII – IP (2025.2026 Material & Old CBSE Questions) 69 2. DataFrames
DELETING ROWS/COLUMNS
Two ways to delete rows and columns – del( ) and drop( )
We can use the DataFrame.drop() method to delete rows and columns from a DataFrame. We need to specify
the names of the labels to be dropped and the axis from which they need to be dropped. To delete a row,
the parameter axis is assigned the value 0 and for deleting a column,the parameter axis is assigned the value
1.
(i) Delete row(s) using drop( ) function: Syntax:<DF>.drop(index or sequence of indexes)
>>> df.drop('Pavan',axis=0,inplace=True)
#df.drop('Pavan',inplace=True)
#df=df.drop('Pavan',axis=0)
# Default axis is 0, so no need to give
>>> df.drop(['Raj','Pavan'],inplace=True)
Note: If the DataFrame has more than one row with the same label, the DataFrame.drop() method will delete
all the matching rows from it.
(Other examples: df.drop(range(2,15,3)) – 2,5,8,11,14
df.drop([2,4,6,8,12])
Argument to drop( ) should be either an index, or a sequence containing indexes.)
(ii) Delete a column, using drop( ) function:
>>> df.drop('Tel',axis=1,inplace=True)
>>>df.drop(['Soc','Eng'],axis=1,inplace=True)
(iii) Delete a column, using del( ) function:
Syntax: del <DF object>[<column name>]
>>> del df['Mat']
HEAD & TAIL FUNCTIONS
head(n ): To display the first n rows in the DataFrame. Default value of n is 5.
Ex:
>>>D={'RNo':[11,12,13,14,15,16,17],'Marks':[60,70,65,50,80,55,90]}
MyDF=pd.DataFrame(D)
>>>MyDF
XII – IP (2025.2026 Material & Old CBSE Questions) 70 2. DataFrames
>>> MyDF.head(3)
# First 3 Rows
>>>MyDF.head( ) # Default – First 5 Rows
>>> MyDF.head(15)
# As 15 is more than total rows, all rows will be displayed.
>>> MyDF.head(-3) # All rows except last 3 rows
tail(n ): To display the last n rows in the DataFrame. Default value of n is 5.
>>>MyDF
>>>MyDF.tail(3) # Last 3 Rows
>>>MyDF.tail( ) # Default – Last 5 Rows
>>>MyDF.tail(777) # As 777 is more than total rows, all rows will be displayed.
>>>MyDF.tail(-3) # All rows except first 3 rows
XII – IP (2025.2026 Material & Old CBSE Questions) 71 2. DataFrames
INDEXING
Data elements in a DataFrame can be accessed using indexing.
There are two ways of indexing Dataframes :
Label based indexing and Boolean Indexing.
LABEL BASED INDEXING
Note: This topic we already covered. But we are also discussing here under this heading “Indexing”
There are several methods in Pandas to implement label based indexing.
DataFrame.loc[ ] is an important method
>>> df.loc['Pavan']
Note: When the row label is passed as an integer value, it is interpreted as a label of the index and not as an
integer position along the index.
Ex:
>>>MyDF = pd.DataFrame([10,20,30,40,50])
>>>MyDF
>>>MyDF.loc[3]
When a single column label is passed, it returns the column as a Series.
>>>df.loc[:,'Mat']
Also, we can obtain the same result that is the marks of ‘Mat’ subject by using the command:
>>>df['Mat']
To read more than one row from a DataFrame, a list of row labels is used as shown below.
Note that using [[ ]] returns a DataFrame.
>>>df.loc[['Mohan', 'Raj']]
XII – IP (2025.2026 Material & Old CBSE Questions) 72 2. DataFrames
BOOLEAN INDEXING
Boolean Indexing – NCERT
Boolean means a binary variable that can represent
either of the two states - True (indicated by 1) or False (indicated by 0).
In Boolean indexing, we can select the subsets of data based on the actual values in the DataFrame
rather than their row/column labels.
Thus, we can use conditions on column names to filter data values.
Consider the above DataFrame df, the following statement displays True or False depending on
whether the data value satisfies the given condition or not.
>>> df.loc['Mohan']>75
To check scores of ‘Mat’ subject, who scored more than 75, we can write:
>>> df.loc[:,'Mat']>75
----------------------------------------------------------
Boolean Indexing Example 2 (From Other Material)
import pandas as pd
import numpy as np
dic = {'std1':{'no':101,'name':'hari','city':'tenali'},
'std2':{'no':102,'name':'vasu','city':'guntur'},
'std3':{'no':103,'name':'kishore','city':'bapatla'}}
df = pd.DataFrame(dic)
print(df)
***
std1 std2 std3
no 101 102 103
name hari vasu kishore
city tenali guntur bapatla
***
lis = pd.DataFrame([[12,14,16],[18,20,22],[24,26,28]])
print(lis)
***
0 1 2
0 12 14 16
1 18 20 22
2 24 26 28
***
lis>20
***
0 1 2
0 False False False
1 False False True
2 True True True
***
lis[lis>20]
***
0 1 2
0 NaN NaN NaN
1 NaN NaN 22.0
2 24.0 26.0 28.0
***
XII – IP (2025.2026 Material & Old CBSE Questions) 73 2. DataFrames
lis.loc[1]>20
***
0 False
1 False
2 True
Name: 1, dtype: bool
***
#creating a dataframe
dic1 = {'kiran':{'mat':67,'sci':89,'soc':93},
'rajani':{'mat':95,'sci':96,'soc':99},
'rani':{'mat':99,'sci':100,'soc':91}}
df2 = pd.DataFrame(dic1)
print(df2)
***
kiran rajani rani
mat 67 95 99
sci 89 96 100
soc 93 99 91
***
#filtering on row
df2.loc['mat']>90
***
kiran False
rajani True
rani True
Name: mat, dtype: bool
***
#filtering on column
df2.loc[:,'rajani']>95
***
mat False
sci True
soc True
Name: rajani, dtype: bool
***
#according to sumitha arora
df2>90
***
kiran rajani rani
mat False True True
sci False True True
soc True True True
***
#according to sumitha arora
df2[df2>90]
***
kiran rajani rani
mat NaN 95 99
sci NaN 96 100
soc 93.0 99 91
------------------------------------------------------------
Boolean Indexing
(Other famous material)
Boolean Indexing, refers to having Boolean Values [(True or False) or (1 or 0) sometimes] as indexes of a
dataframe.
The Boolean indexes divide the dataframe in two groups – True rows and False rows.
In some situations, we may need to divide our data in two subsets – True or False, e.g., your school
has decided to launch online classes for you. But some days of the week are designated for it. So, a dataframe
related to this information might look like:
XII – IP (2025.2026 Material & Old CBSE Questions) 74 2. DataFrames
Day No.of Classes
True Monday 5
False Tuesday 0
True Wednesday 3
False Thursday 4
True Friday 7
True Saturday 2
This is useful division in situations where we find out things like – On which days, the online classes
are held? Or which ones are offline classes days? And so on.
Creating DataFrames with Boolean Indexing:
While creating a dataframe with Boolean indexes True and False, we should not enclosed in quotes
(Otherwise, KeyError will generates)
Create a dataframe containing online classes information, through the code :
import pandas as pd
Days=['Mon','Tue','Wed','Thu','Fri','Sat']
Classes = [5,0,3,4,7,2]
dict={'Days':Days,'No.of Classes':Classes}
df=pd.DataFrame(dict,
index=[True,False,True,False,True,True])
print(df)
We can also provide Boolean indexing to dataframes as 1s and 0s.
df=pd.DataFrame(dict,index=[1,0,1,0,1,1])
Accessing Rows from DataFrames with Boolean Indexing:
Boolean indexing is very useful for filtering records i.e., for finding or extracting the True or False indexed
rows.
<DF>.loc[True] Display all records with True index
<DF>.loc[False] Display all records with False index
<DF>.loc[1] Display all records with index as 1
<DF>.loc[0] Display all records with index as 0
Ex: Days=['Mon','Tue','Wed','Thu','Fri','Sat']
Classes = [5,0,3,4,7,2]
dict={'Days':Days,'No.of Classes':Classes}
df=pd.DataFrame(dict,index=[True,False,True,False,True,True])
>>>df.loc[True] #df.loc[1]
>>>df.loc[False] #df.loc[0]
------------------------------------------------------------
XII – IP (2025.2026 Material & Old CBSE Questions) 75 2. DataFrames
Accessing DataFrames Element through Slicing:
We can use slicing to select a subset of rows and/or columns from a DataFrame. To retrieve a set of rows,
slicing can be used with row labels.
For example: >>>df.loc['Pavan':'Mohan']
Here, the rows with labels Pavan and Mohan are displayed.
Note that in DataFrames slicing is inclusive of the end values. We may use a slice of labels with a column
name to access values of those rows in that column only.
For example, the following statement displays the rows with label Raj and Mohan, and column with
label Soc: >>> df.loc[['Raj','Mohan'],'Soc']
>>> df.loc['Pavan', 'Eng':'Mat']
>>> df.loc['Raj': 'Mohan', 'Tel':'Soc']
>>>df.loc['Pavan': 'Mohan',['Eng','Mat']]
Filtering Rows in DataFrames :
In DataFrames, Boolean values like True (1) and False (0) can be associated with indices. They can also be
used to filter the records using the DataFrame.loc[ ] method.
In order to select or omit particular row(s), we can use a Boolean list specifying ‘True’ for the rows to be
shown and ‘False’ for the ones to be omitted in the output.
For example, in the following statement, row having index as Science is omitted:
>>> df.loc[[True, False, True]]
>>> df.loc[[True, True, False]]
>>> df.loc[[False, True, True]]
>>> df.loc[[True, True, True]]
>>> df.loc[[False,False,False]]
XII – IP (2025.2026 Material & Old CBSE Questions) 76 2. DataFrames
BINARY OPERATIONS IN A DATAFRAME
Binary operations mean operations requiring two values to perform and these values are picked
element wise.
In a binary operation, the data from two dataframes are aligned on the bases of their row and column
indexes and for the matching row, column index, the given operation is performed and for the nonmatching
row, column index NaN value is stored in the result.
Data is aligned in two dataframes, the data is aligned on the basis of matching row and column indexes
and then arithmetic is performed for non-overlapping indexes, the arithmetic operations result as a NaN for
non-matching indexes.
Binary Operations:
addition, subtraction, multiplication, division
Example Data Frames : DF1, DF2, DF3, DF4
DF 1 DF2 DF3 DF4
import pandas as pd
dict1={'A':[11,17,23],'B':[13,19,25],'C':[15,21,27]}
DF1=pd.DataFrame(dict1)
dict2={'A':[12,18,24],'B':[14,20,26],'C':[16,22,28]}
DF2=pd.DataFrame(dict2)
dict3={'A':[1,3,5],'B':[2,4,6]}
DF3=pd.DataFrame(dict3)
dict4={'A':[7,9],'B':[8,10]}
DF4=pd.DataFrame(dict4)
Addition : [ Using +, add( ), radd( ) ]
Note : DF1.add(DF2) is equal to DF1+DF2
DF1.radd(DF2) is equal to DF2+DF1
radd( ) means reverse addition
>>>DF1+DF2 #DF1.add(DF2)
>>>DF1+DF3 >>>DF1+DF4
>>>DF2+DF3 >>>DF2+DF4
>>>DF3+DF4 >>>DF3.add(DF4)
XII – IP (2025.2026 Material & Old CBSE Questions) 77 2. DataFrames
Subtraction: [ Using -, sub( ), rsub( ) ]
Note : DF1.sub(DF2) is equal to DF1-DF2 DF1.rsub(DF2) is equal to DF2-DF1
rsub( ) means reverse subtraction
>>>DF1-DF2 >>>DF2-DF1
>>>DF1-DF3 >>>DF3-DF1
>>>DF1-DF4 >>>DF4-DF1
>>>DF2-DF3 >>>DF3-DF2
>>>DF2-DF4 >>>DF4-DF2
>>>DF3-DF4 >>>DF4-DF3
#DF3.sub(DF4) #DF3.rsub(DF4)
Multiplication: [ Using *, mul( ), rmul( ) ]
Note : DF1.mul(DF2) is equal to DF1*DF2 DF1.rmul(DF2) is equal to DF2*DF1
rmul( ) means reverse multiplication
>>>DF1*DF2 >>>DF1*DF3
>>>DF1*DF4 >>>DF2*DF3
>>>DF2*DF4 >>>DF3*DF4
XII – IP (2025.2026 Material & Old CBSE Questions) 78 2. DataFrames
Division: [ Using /, div( ), rdiv( ) ]
Note : DF1.div(DF2) is equal to DF1/DF2 DF1.rdiv(DF2) is equal to DF2/DF1
rdiv( ) means reverse division.
>>>DF1/DF2
>>>DF2/DF1
>>>DF1/DF3
>>>DF3/DF1
>>>DF1/DF4
>>>DF2/DF3
>>>DF3/DF2
>>>DF2/DF4
>>>DF4/DF2
>>>DF3/DF4
>>>DF4/DF3
XII – IP (2025.2026 Material & Old CBSE Questions) 79 2. DataFrames
DATAFRAME ATTRIBUTES
All information related to a DataFrame such as its size, datatype, etc is available through its attributes.
Syntax to use a specific attribute:
<DataFrame object>.<attribute name>
Attribute Description
index To display/assign index (row labels) of the DataFrame.
columns To display/assign the column labels of the DataFrame.
axes It returns both axis 0 i.e., index and axis 1 i.e., columns of the DataFrame.
dtypes to display data type of each column in the DataFrame.
values to display a NumPy ndarray having all the values in the DataFrame,without the axes labels.
shape Return a tuple representing the dimensionality of the DataFrame ., (no.of rows, no.of columns)
size Return an int representing the number of elements in this object.
empty To returns the value True if DataFrame is empty and False otherwise
ndim Return an int representing the number of axes/array dimensions.
T To Transpose the DataFrame. Means, row indices and column labels of the DataFrame
replace each other’s position
Example of a DataFrame DF:
import pandas as pd
>>>dict={'Eng':[68,72,66],'Tel':[55,84,90]}
>>>df=pd.DataFrame(dict,index=['Raj','Pavan','Mohan'])
>>>df
Retrieving various properties of a DataFrame Object:
>>>df.index
Index(['Raj', 'Pavan', 'Mohan'], dtype='object')
>>> df.index=['A','B','C']
>>> df.columns
Index(['Eng', 'Tel'], dtype='object')
>>>df.columns=['M','N']
>>>df
Again let us consider the original DataFrame.
>>> df.axes
[Index(['Raj', 'Pavan', 'Mohan'], dtype='object'), Index(['Eng', 'Tel'], dtype='object')]
>>> df.dtypes
>>>df.values # Numpy representation
>>> df.shape #(no.of rows, no.of columns)
(3,2)
>>> df.size
6 #3rows X columns
>>> df.empty #if DataFrame is empty, gives True
False
XII – IP (2025.2026 Material & Old CBSE Questions) 80 2. DataFrames
>>>df.ndim # As DataFrame is a 2 Dimensional
2
>>>df.T #Transpose. Rows will become columns and vice versa.
Others
Function Description
len(<DF Return the number of rows in a dataframe
Object>)
(<DF Object>. If we pass any argument or 0 (default is 0), it returns count of non-NA values for
count( ) each column, if it is 1, it returns count of non-NA values for each row.
>>>len(df)
4
>>>df.count( )#df.count(0)or df.count(axis=’index’)
RNo 4
SName 4
Marks 4
dtype: int64
>>>df.count(1) # df.count(axis=’columns’)
First 3
Second 3
Third 3
Fourth 3
dtype: int64
>>>df.shape[0]# to get number of rows
4
>>>df.shape[1]# to get number of columns
3
XII – IP – CBSE OLD QUESTIONS
DATAFRAMES
1.CBSE BOARD PAPER::2024.25
1. Which of the following Python statements is used to change a column label in a DataFrame, df ?
(A) df = df.rename({old_name : new_name}, axis='columns')
(B) df = df.rename(old_name, new_name), axis='columns'
(C) df = df.change_name(old_name, new_name, axis='bar')
(D) df = df.update({old_name : new_name}, axis='bar')
2. In Python Pandas, DataFrame. ________ [] is used for label indexing with DataFrames.
(A) label (B) index (C) labindex (D) loc
3. Assertion (A) and Reason (R) type questions. Choose the correct option as :
(A) Both Assertion (A) and Reason (R) are True and Reason (R) is the correct explanation for Assertion (A).
(B) Both Assertion (A) and Reason (R) are True and Reason (R) is not the correct explanation for Assertion
(A).
(C) Assertion (A) is True and Reason (R) is False.
(D) Assertion (A) is False, but Reason (R) is True.
Assertion (A) : The drop() method in Pandas can be used to delete rows and columns from a DataFrame.
XII – IP (2025.2026 Material & Old CBSE Questions) 81 2. DataFrames
Reason (R) : The axis parameter in the drop() method specifies whether to delete rows (axis=0) or columns
(axis=1).
4. Mention any two main points of difference between Series and DataFrame of Python Pandas.
5. Explain how we can access elements of a series using slicing. Give an example to support your answer.
6. Complete the given Python code to generate the following output :
COLOUR NAME QTY
0 Red Apple 10
1 Blue Berry 15
2 Green Guava 20
import _________ as pd
data=[{'COLOUR':'Red', 'NAME':'Apple', 'QTY':10},
{'COLOUR':'Blue','NAME':'Berry', 'QTY':15},
{___________, 'NAME' :'Guava','QTY':20}]
df=pd.DataFrame(__________)
print(____________)
7. Write a Python program to create the following DataFrame using a Dictionary of Series :
City State
0 Mumbai Maharashtra
1 Dehradun Uttarakhand
2 Bengaluru Karnataka
3 Hyderabad Telangana
8. Consider the DataFrame Doctor shown below:
Write suitable Python statements for the following:
(i) To print the last three rows of the DataFrame Doctor.
(ii) To display the names of all doctors.
(iii) To add a new column 'Discount' with value of 200 for all doctors.
(iv) To display rows with index 2 and 3.
(v) To delete the column 'Department'.
CBSE Board Paper :: 2024.25 (ANSWERS)
1) (A) df = df.rename({old_name : new_name}, axis='columns')
2. A) (D) loc
3. A
4.
Series DataFrame
Series is one-dimensional DataFrame is two-dimensional
Series is used for storing a single column of DataFrame is used for storing multiple columns of
data. data.
Elements in Series must be homogeneous Elements in DataFrame may be heterogeneous.
Elements in Series are accessed using a single Elements in DataFrame are accessed using two
index. indices.
Size of Series is immutable Size of DataFrame is mutable
5. Elements of a series can be accessed in any of the following ways using slicing:
Example:
Considering data to be a pandas series containing values [10, 20, 30, 40, 50] having index as ['a','b','c','d','e']
XII – IP (2025.2026 Material & Old CBSE Questions) 82 2. DataFrames
Positional Indexing/ Integer-based slicing: Slice a Series using indices
# Slice the Series from the first to the third element
data[0:3] OR data.iloc[0:3]
Label-based slicing: Slice a Series using its index labels.
data['b':'d'] OR data.loc['b':'d']
Conditional slicing: Slice a Series based on condition.
# Slice the Series where values are greater than 30
#for a pandas series named as data
data[data > 30]
6.
import pandas as pd
data= [{'COLOUR':'Red' , 'NAME': 'Apple' , 'QTY' : 10},
{'COLOUR':'Blue' , 'NAME': 'Berry' , 'QTY' : 15},
{'COLOUR':'Green' , 'NAME': 'Guava' , 'QTY' : 20}]
df=pd.DataFrame(data)
print(df)
7.
import pandas as pd
d={ 'City':pd.Series( ['Mumbai','Dehradun','Bengaluru','Hyderabad']), 'State': pd.Series(
['Maharashtra','Uttarakhand' , 'Karnataka' , 'Telangana'])
}
df=pd.DataFrame(d)
print(df)
OR
import pandas as pd
City=pd.Series(['Mumbai','Dehradun','Bengaluru','Hyderabad'])
State=pd.Series(['Maharashtra','Uttarakhand','Karnataka','Telangana'])
df=pd.DataFrame({'City':City, 'State':State})
print(df)
8.
(i) print(doctor.tail(3)) OR print(doctor.iloc[-3:])
(ii) print(doctor['Name']) OR print(doctor.iloc[:,[1]])
OR print(doctor.loc[:,['Name']])
(iii) doctor['Discount']=200 OR doctor.loc[:, "Discount"] = 200
(iv) print(doctor.loc[[2,3]]) OR print(doctor.iloc[[2,3]])
OR print(doctor[2:4])
(v) doctor.drop(['Department'],axis=1, inplace=True)
OR doctor = doctor.drop(['Department'],axis=1)
Note: axis=1 can be replaced with axis= 'columns'
2.CBSE COMPARTMENT PAPER::2024.25
1. Which of the following command is used to display first three rows of a DataFrame 'DF' ?
(A)DF.head() (B)DF.header() (C)DF.head(3) (D) DF.Head(3)
2. The Python code written below has syntactical errors. Rewrite the correct code and underline the
correction(s) made.
import Pandas as pd countries=[{'country';'INDIA','capital':'New Delhi'},
{'country':'USA','capital':'New York'}, {'country':'JAPAN','capital':'Tokyo'}
df=pd.DataFrame(country)
print(df)
XII – IP (2025.2026 Material & Old CBSE Questions) 83 2. DataFrames
3. Consider the following Python code :
import pandas as pan
customer =[{'Name':'Alisha','Age':25,'Gender':'Female','Occupation':'Engineer'},
{'Name':'Rozer','Age':34,'Gender':'Male',______: 'Analyst'},
{'Name':'Fazal','Age':28,'Gender':'Male','Occupation':'Developer'}]
df= _________.DataFrame(__________)
print(_________)
Complete the above given Python code to display the following output :
4. Sejal, a Python programmer has been given the following tasks :
(i) Create two series – one to store various product names and the other to store the corresponding price.
Each series should have appropriate row label as given below :
(ii) Create a dictionary containing ‘Product_name’ and ‘Product_price’ as keys. Add the series created in
part (i) as their corresponding values.
(iii) Create a DataFrame from the above created dictionary of series.
Help her in writing the Python program to accomplish the above mentioned tasks.
5. Consider the following DataFrame Cricket :
Write suitable Python statements to perform the following tasks :
(i) Add a new column Rating to the DataFrame having the following values : 3, 1, 2, 4, 5
(ii) Change the row labels from A, B, C, D, E to Team A, Team B, Team C, Team D and Team E.
(iii) Change the column label of first column from 'Won' to 'Matches won'.
6. Ms. Shambhavi, a data analyst working on a college admission project, has created the following
DataFrame Sub_Details to store subjectwise details :
XII – IP (2025.2026 Material & Old CBSE Questions) 84 2. DataFrames
(i) Write suitable Python command to display the row having index value 3.
(ii) Predict the output of the following Python statement :
print(Sub_Details.loc[2:3,'Total Students'])
(iii) (a) Write suitable Python statement to display the list of various subjects along with their corresponding
seat availability.
OR [option for part (iii) only]
(b) Ms. Shambhavi has just created a folder named Project in the E: drive of her computer to store necessary
files related to the project. Write suitable Python statement to export the given DataFrame into the file
stud.csv, created inside project folder in E: drive.
CBSE Compartment Paper :: 2024.25 (ANSWERS)
1. A) DF.head(3)
2. import pandas as pd
countries=[{'country':'INDIA','capital':'New Delhi'}, {'country':'USA','capital':'New York'},
{'country':'JAPAN','capital':'Tokyo'}]
df=pd.DataFrame(countries)
print(df)
3.
import pandas as pan
customer=[{'Name':'Alisha','Age':25,'Gender':'Female', 'Occupation':'Engineer'},
{'Name':'Rozer','Age':34,'Gender':'Male','Occupation':'Analyst'},
{'Name':'Fazal','Age':28,'Gender':'Male', 'Occupation':'Developer'}]
df= pan.DataFrame(customer)
print(df)
4.
(i) import pandas as pd
D1=['Butterscotch','Vanilla','Mango Zap','Magnum','Cassatta']
D2=[130,100,150,190,200]
I=['B1001','V3002','M4002','M4007','C6005']
S1=pd.Series(D1,I)
S2=pd.Series(D2,I)
(ii) D={'Product_name':S1,'Product_price':S2}
(iii) DF=pd.DataFrame(D)
5.
(i) Cricket['Rating']=[3,1,2,4,5]
(ii) Cricket.rename(index={"A":"Team A", "B":"Team B", "C":"Team C", "D":"Team D", "E":"Team E"},
inplace=True)
(iii) Cricket.rename(columns={"Won":"Matches won"}, inplace=True)
6.
(i) print(Sub_Details[2:3]) OR print(Sub_Details.loc[3])
(ii) 2 45
3 40
Name: Total Students, dtype: int64
(iii) (a) print(Sub_Details[['Subject','Seat Availability']]) OR
(b) Sub_Details.to_csv("E:\project\stud.csv") OR
Sub_Details.to_csv("E:/project/stud.csv") OR
XII – IP (2025.2026 Material & Old CBSE Questions) 85 2. DataFrames
Sub_Details.to_csv("E:\\project\\stud.csv") OR
Sub_Details.to_csv(r"E:\project\stud.csv")
3.CBSE SAMPLE PAPER::2024.25
DATAFRAMES ( 14 Marks)
4 MCQs, 2 Marks, 3 Marks, 5 Marks
DataFrame creation using different methods
Complete the missing code of DataFrame
DataFrame Operations
6. Which of the following Python statements can be used to select a column column_name from a
DataFrame df ?
(A)df.getcolumn('column_name') (B) df['column_name']
(C) df.select('column_name') (D) df(column_name)
A) (B)df['column_name']
13. In a Pandas DataFrame, if the tail() function is used without specifying the optional argument indicating
the number of rows to display, what is the default number of rows displayed, considering the DataFrame has
10 entries?
(A) 0 (B) 1 (C) 4 (D) 5
A) (D) 5
17. Fill in the Blank
Boolean indexing in Pandas DataFrame can be used for _______.
(A)Creating a new DataFrame (B) Sorting data based on index labels
(C) Joining data using labels (D) Filtering data based on condition
A) (D)Filtering data based on condition
20. Q-20 and Q-21 are Assertion (A) and Reason (R) Type questions. Choose the correct option as:
(A)Both Assertion (A) and Reason (R) are true, and Reason (R) is the correct explanation of Assertion (A)
(B)Both Assertion (A) and Reason (R) are true, but Reason (R) is not the correct explanation of Assertion (A)
(C)Assertion (A) is True, but Reason (R) is False
(D)Assertion (A) is False, but Reason (R) is True
20. Assertion (A): We can add a new column in an existing DataFrame.
Reason (R): DataFrames are size mutable.
A) (A) Both Assertion (A) and Reason (R) are true, and Reason (R) is the correct explanation of Assertion (A)
28. Sneha is writing a Python program to create a DataFrame using a list of dictionaries. However,
her code contains some mistakes. Identify the errors, rewrite the correct code, and underline the
corrections made.(2m)
import Pandas as pd
D1 = {'Name': 'Rakshit', 'Age': 25}
D2 = {'Name': 'Paul', 'Age': 30}
D3 = {'Name': 'Ayesha", 'Age': 28}
data = [D1,D2,D3)
df = pd.Dataframe(data)
print(df)
A)
import pandas as pd
D1 = {'Name': 'Rakshit', 'Age': 25}
D2 = {'Name': 'Paul', 'Age': 30}
D3 = {'Name': 'Ayesha', 'Age': 28}
data = [D1, D2, D3]
df = pd.DataFrame(data)
print(df)
Changes Made :
i. Changed Pandas to pandas.
ii. Corrected mismatched string quotation marks
iii. Corrected the closing parenthesis in the list data.
XII – IP (2025.2026 Material & Old CBSE Questions) 86 2. DataFrames
iv. Changed Dataframe to DataFrame. (1/2 mark for each correct correction and
underlining)
30. Write a Python program to create the following DataFrame using a list of dictionaries. (3m)
A) import pandas as pd
d1 = {'Product': 'Laptop', 'Price': 60000}
d2 = {'Product': 'Desktop', 'Price': 45000}
d3 = {'Product': 'Monitor', 'Price': 15000}
d4 = {'Product': 'Tablet', 'Price': 30000}
data = [d1, d2, d3, d4]
df = pd.DataFrame(data)
print(df)
(1 mark for correct import statement)(1 mark for correct list of dictionary)(1 mark for correct creation of DataFrame)
36. Consider the DataFrame df shown below. (5m)
Write Python statements for the DataFrame df to:
I. Print the first two rows of the DataFrame df.
A) print(df.head(2))
II. Display titles of all the movies.
A) print(df['Title'])
III. Remove the column rating.
A) df = df.drop(‘Rating’, axis=1)
IV. Display the data of the 'Title' column from indexes 2 to 4 (both included)
A) print(df.loc[2:4,'Title'])
V. Rename the column name 'Title' to 'Name'.
A) df.rename(columns={'Title':'Name'}, inplace=True)
4.CBSE BOARD PAPER::2023.24
18. Assertion (A) : A Series is a one dimensional array and a DataFrame is a two-dimensional array
containing
sequence of values of any data type. (int, float, list, string, etc.)
Reason (R) : Both Series and DataFrames have by default numeric indexes starting from zero.
(i) Both (A) and (R) are true and (R) is the correct explanation for (A).
(ii) Both (A) and (R) are true and (R) is not the correct explanation for (A).
(iii) (A) is true and (R) is false.
(iv) (A) is false but (R) is true.
20. The Python code written below has syntactical errors. Rewrite the correct code and underline the
correction(s) made.
import Pandas as pd
stud=['Name':'Ramya','Class':11,'House':'Red']
s=p.Series(s)
print(s)
Ans)
import pandas as pd
stud = {'Name':'Ramya', 'Class':11, 'House':'Red'}
s = pd.Series(stud)
print(s)
24. Consider the following Python code :
XII – IP (2025.2026 Material & Old CBSE Questions) 87 2. DataFrames
import pandas as pd
Sl=pd.Series(['Rubina','Jaya','Vaibhav'],index=[10,16,18])
S2=pd.Series(_________ , index=[10,16,18])
S3=pd.Series([56,67,86], __________ )
xiia={'Name':______ ,'Subject':S2,'Marks':S3}
df=pd.DataFrame(________)
print(df)
Complete the above Python code to display the following output :
A) import pandas as pd
S1=pd.Series(['Rubina','Jaya','Vaibhav'], index=[10,16,18])
S2=pd.Series(['IP','HSc','IP'], index=[10,16,18])
S3=pd.Series([56,67,86], index=[10,16,18])
xiia={'Name':S1, 'Subject':S2, 'Marks':S3}
df=pd.DataFrame(xiia)
print(df)
27. Kabir, a data analyst, has stored the voter's name and age in a dictionary. Now, Kabir wants to
create a list of dictionaries to store data of multiple voters. He also wants to create a DataFrame from
the same list of dictionaries having appropriate row labels as shown below :
Help Kabir in writing a Python program to complete the task.
A) import pandas as pd
voters=[{"Voter_Name":"Arjun", "Voter_Age":35}, {"Voter_Name":"Bala", "Voter_Age":23},
{"Voter_Name":"Govind", "Voter_Age":25},{"Voter_Name":"Dhruv", "Voter_Age":19},
{"Voter_Name":"Navya", "Voter_Age":18}]
dfVoters=pd.DataFrame(voters, index=["Ar1001","Ba3002","Go4002","Dh4007","Na6005"])
print(dfVoters)
30. Consider the given DataFrame 'password':
Write suitable Python statements for the following :
(i) To add a new row with following values :
CodeName - 'abc123'
Category - alphanumeric
Frequency - 12.8
A) password.loc[7]=['abc123','alphanumeric',12.8] OR
password.at[7]=['abc123','alphanumeric',12.8] OR
password.loc[len(password)] = ['abc123','alphanumeric',12.8] OR
password.at[len(password)] = ['abc123','alphanumeric',12.8] OR
password.loc[len(password.index)] = ['abc123','alphanumeric',12.8] OR
XII – IP (2025.2026 Material & Old CBSE Questions) 88 2. DataFrames
password.at[len(password.index)] = ['abc123','alphanumeric',12.8] OR
password.loc[7,:]=['abc123','alphanumeric',12.8] OR
password.at[7,:]=['abc123','alphanumeric',12.8] OR
password=password.append({"CodeName":"abc123","Category":"alpha numeric","Frequency":12.8},
ignore_index=True) OR
df1=pd.DataFrame({"CodeName":["abc123"],"Category":["alphanumer ic"],"Frequency":[12.8]})
OR
password=pd.concat([password,df1], ignore_index=True)
(ii) To delete the row with the row label 2.
A) password.drop(2, inplace=True) OR
password.drop(2, inplace=True, axis=0) OR
password.drop(labels=2, inplace=True) OR
password.drop(labels=2, axis=0, inplace=True) OR
password.drop([2], inplace=True) OR
password.drop([2], axis=0, inplace=True) OR
password=password.drop([2]) OR
password=password.drop([2], axis=0) OR
password.drop([password.index[2]], inplace=True) OR
password.drop(password.index[2:3], inplace=True)
(iii) To delete the column having column label as Frequency.
A) password.drop("Frequency", axis=1, inplace=True) OR
password.drop(columns=['Frequency'], inplace=True) OR
password.drop(password.columns[2], axis=1, inplace=True) OR
password.drop(password.iloc[:, 2:], inplace=True, axis=1) OR
password.drop(password.loc[:, "Frequency":].columns, inplace=True, axis=1)
32) Ms. Ritika conducted an online assessment and stored the details in a DataFrame result as given
below :
Answer the following questions :
(i) Predict the output of the following Python statement:
print(result.loc [:,'Attempts'] > 1)
A) A False
B True
C True
D False
Name: Attempts, dtype: bool
(ii) Write the Python statement to display the last three records.
A) print(result.tail(3)) OR
print(result.iloc[1:]) OR
print(result.iloc[1:4]) OR
print(result.iloc[[1,2,3],:]) OR print(result.loc[["b","c","d"]])
(iii) Write Python statement to display records of 'a ' and 'd' row labels.
A) print(result.loc[["a","d"]]) OR
print(result.iloc[[0,3],:])
(OR)
(iii) (Option for Part (iii) only)
Write suitable Python statement to retrieve the data stored in the file, 'registration.csv' into a
DataFrame, 'regis'.
A) regis=pd.read_csv("registration.csv")
XII – IP (2025.2026 Material & Old CBSE Questions) 89 2. DataFrames
5.CBSE Additional Practice Paper ::2023.24
11. Assertion (A) : A DataFrame and its size is mutable in Pandas.
Reasoning (R) : Data in a Series is organised in a single column.
a. Both A and R are true and R is the correct explanation for A
b. Both A and R are true but R is not the correct explanation for A
c. A is True but R is False
d. A is false but R is True
13. Which of the following function is used in Pandas to display the first few rows of a specific column in a DataFrame?
a. show() b. display() c. head() d. view()
20. Consider the given dataframe
Fill in the blanks to get the given output :
F1 F3
D1 20 5
D3 60 15
a. print (Dataf1.loc[________,______])
F3 F2
D4 25 90
D3 15 70
b. print (Dataf1.loc[________,______])
22. Gaytri, a data analyst has stored four employee’s name and their employee code in four dictionaries Structure of
one such dictionary is as follows:
Emp1={'Ename':'EmpName','Ecode’:Employeecode}
She clubbed these four dictionary into a list.
Write suitable Python code to store the required data of four employees in the form of list of dictionaries and create a
DataFrame with appropriate column headings as shown below:
30. Consider the given DataFrame 'Employees’:
Write suitable Python statements for the following operations:
i)Add a column called 'Salary' with the following data: [55000,60000,65000,58000].
ii)Include a new employee named 'Eve' with Employee_ID 'EMP005', working in the 'Finance' department, and a salary
of 62000.
iii)Change the name of the 'Employee_ID' column to 'ID'.
CBSE Additional Practice Paper :: 2023.24 (ANSWERS)
11. b 13. c 20. a. print(Dataf1.loc[['D1','D3'],['F1','F3']]) b. print(Dataf1.loc[['D4','D3'],['F3','F2']])
22.
import pandas as pd
data=[{'Ename':'John', 'Ecode':88},
{'Ename':'Emily', 'Ecode':92},
{'Ename':'Michael', 'Ecode':78},
{'Ename':'Sophia','Ecode':95}]
df=pd.DataFrame(data)
print(df)
30.i) df['Salary'] = [55000, 60000, 65000, 58000]
ii) Employees.loc[4] = ['Eve', 'EMP005', 'Finance', 62000]
iii) df = df.rename(columns={'Employee_ID': 'ID'})
XII – IP (2025.2026 Material & Old CBSE Questions) 90 2. DataFrames
6.CBSE SAMPLE PAPER::2023.24
20. The python code written below has syntactical errors. Rewrite the correct code and underline the corrections made.
Import pandas as pd
df = {"Technology":["Programming","Robotics",
"3D Printing"],"Time(in months)":[4,4,3]}
df= Pd.dataframe(df)
Print(df)
27. Create a DataFrame in Python from the given list:
[[‘Divya’,’HR’,95000],[‘Mamta’,’Marketing’,97000], [‘Payal’,’IT’,980000], [‘Deepak’,’Sales’,79000] ]
Also give appropriate column headings as shown below:
30. Consider the given DataFrame ‘Genre’:
Write suitable Python statements for the following:
i. Add a column called Num_Copies with the following data: [300,290,450,760].
ii. Add a new genre of type ‘Folk Tale' having code as “FT” and 600 number of copies.
iii. Rename the column ‘Code’ to ‘Book_Code’.
32. Ekam, a Data Analyst with a multinational brand has designed the DataFrame df that contains the four quarter’s
sales data of different stores as shown below:
Answer the following questions:
i. Predict the output of the following python statement:
a. print(df.size) b. print(df[1:3])
ii. Delete the last row from the DataFrame.
iii. Write Python statement to add a new column Total_Sales which is the addition of all the 4 quarter sales.
CBSE SAMPLE PAPER :: 2023.24 (ANSWERS)
20.
import pandas as pd
df = {"Technology": ["Programming", "Robotics",
"3D Printing"],"Time(in months)":[4,4,3]}
df= pd.DataFrame(df)
print(df)
27.
import pandas as pd #Statement 1
df=[["Divya","HR",95000],["Mamta","Marketing", 97000],["Payal","IT",980000], ["Deepak","Sales",79000]]
#Statement 2
df=pd.DataFrame(df,columns=["Name",Department","Salary"]) #Statement 3
print(df) #Statement 4
30. i. Genre["Num_Copies"]=[300,290,450,760]
ii. Genre.loc[4]=["Folk Tale","FT",600]
iii. Genre=Genre.rename({"Code":"Book_Code"}, axis=1)
OR
Genre=Genre.rename({"Code":"Book_Code"}, axis="columns")
32 . i. a. 15
b. Store Qtr1 Qtr2 Qtr3 Qtr4
1 Store2 350 340 403 210
2 Store3 250 180 145 160
ii. df=df.drop(2) OR df.drop(2,axis=0)
iii. df["total"]=df["Qtr1"]+df["Qtr2"]+df["Qtr3"]+df["Qtr4"]
XII – IP (2025.2026 Material & Old CBSE Questions) 91 2. DataFrames
7.CBSE COMPARTMENT::2022.23
10. What will be the output of the Python program mentioned below ?
import pandas as pd
df=pd.DataFrame(['Apple','Banana','Orange','Grapes', 'Guava'])
print(df[2:4:2])
a) 0
2 Banana
b) 0
2 Orange
(c) 0
2 Banana
4 Grapes
(d) Empty DataFrame
Columns:[0]
Index:[ ]
22. Shobit needs to create the following two series named ‘Eng’ and ‘Math’. Help him to create a DataFrame ‘mydata’ from
the given series ‘Eng’ and ‘Math’.
25. Carefully observe the following code :
import pandas as pd
product={'prodid':pd.Series([1,2,3,4,5]),
'pname':pd.Series(['pen', 'pencil', 'eraser',
'color', 'sharpener']),
'qty':pd.Series([2,10,10,30,10]),
'price':pd.Series([300,20,50,40,15])}
stock=pd.DataFrame(product)
print(stock)
Write Python statements for the following :
(i) Display the names of products.
(ii) Rename the column ‘price’ to ‘newprice’ in the DataFrame stock.
35. Consider the following DataFrame ‘employee’:
a.i) Write Python statements for the DataFrame ‘employee’:
ii) To remove the row having index 4.
b) Write Python statement to save the DataFrame ‘employee’ to a CSV file data.csv stored in D: drive of the
computer
(OR) only for b
b) Write a Python statement to display the new salary i.e., salary increased by 5000 for all employees.
ANSWERS
10. (b) 0
2 Orange
22. import pandas as pd
eng_data = {‘Aditi’: 25, ‘bhavuk’: 21, ‘chirag’: 23, ‘deepak’: 24, ‘Gaurav’: 27}
Eng = pd.Series(eng_data, name=’Eng’)
math_data = {‘Aditi’: 9, ‘bhavuk’: 29, ‘chirag’: 15, ‘deepak’: 14, ‘Gaurav’: 20}
Math = pd.Series(math_data, name=’Math’)
mydata = pd.DataFrame({‘Eng’: Eng, ‘Math’: Math})
XII – IP (2025.2026 Material & Old CBSE Questions) 92 2. DataFrames
OR
import pandas as pd
Eng = pd.Series([25,21,23,24,27],
index=[‘Aditi’,’bhavuk’,’chirag’,’deepak’,’Gaurav’], name=’Eng’)
Math = pd.Series([9,29,15,24,20],
index=[‘Aditi’,’bhavuk’,’chirag’,’deepak’,’Gaurav’], name=’Math’)
mydata = pd.concat([Eng, Math], axis=1)
25. (i) print(stock[‘pname’])
(ii) stock.rename({‘price’:’newprice’},axis=’columns’, inplace=True) OR
(ii)stock.rename({‘price’:’newprice’},axis=1, inplace=True) OR
(ii) stock.columns = [‘prodid’, ‘pname’, ‘qty’, ‘newprice’]
35.a.i) employee=employee.drop(‘Salary’, axis=1) OR
employee.drop(‘Salary’, axis=1, inplace=True)
ii) employee=employee.drop(employee.index[4]) OR
employee.drop(employee.index[4], inplace=True)
b) employee.to_csv(‘d:\\data.csv’) OR
employee.to_csv(‘d:/data.csv’)
(OR) for option b
employee['new_salary'] = employee['salary'] + 5000
print(employee['new_salary']) OR
print(employee['salary']+5000)
8. CBSE BOARD PAPER::2022.23
11. Which of the following is a two-dimensional labelled data structure of Python?
(i) Relation (ii) Dataframe (iii) Series (iv) Square
25. Carefully observe the following code:
import pandas as pd
dic={'pid': [101, 102, 103, 104, 105], 'pname': ['Shyam', 'Roushan', 'Archit', 'Medha', 'Lalit'],
'sports': ['Cricket', 'Tennis', 'Football', 'Cricket','Cricket'], 'points': [45000,20000, 15000, 53000, 60000]}
player=pd.DataFrame (dic)
print (player)
Write Python statements for the following:
(i) In the dataframe player created above, set the row labels as 'Player1', 'Player2', 'Player3', 'Player4', 'Player5'.
(ii) Rename the column 'points' to 'netpoint' in the DataFrame player.
27. Kavyanjali, a chemical analyst, needs to arrange data of few elements in the form of two series containing symbols
and their atomic numbers respectively. Thereafter, the data of these two series has to be arranged and displayed in the
form of Data Frame as shown below:
Symbol Atomic Number
Hydrogen H 1
Helium He 2
Lithium Li 3
Beryllium Be 4
Help her in writing suitable Python code to complete the task.
28. Consider the given DataFrame 'health'.
Diseasename Agent
0 Common cold Virus
1 Chickenpox Virus
2 Cholera Bacteria
3 Tuberculosis Bacteria
Write suitable Python statements for the following:
(i) Remove the row containing details of disease named Tuberculosis.
(ii) Add a new disease named 'Malaria' caused by 'Protozoa'
(iii) Display the last 2 rows.
CBSE BOARD PAPER::2022.23::ANSWERS
11) (ii) Dataframe
25) i) player=pd.DataFrame (dic,index= ['Player1','Player2','Player3','Player4','Player5']) OR
I=['Player1','Player2','Player3','Player4','Player5']
player=pd.DataFra me (dic,index=I)
XII – IP (2025.2026 Material & Old CBSE Questions) 93 2. DataFrames
ii) player=player.rename({'points':'netpoints'}, axis='columns') OR
player.rename({'points':'netpoints'},axis='columns', inplace=True) OR
player=player.rename({'points':'netpoints'},axis=1) OR
player=player.rename(columns={'points':'netpoints'}) OR
player.rename({'points':'netpoints'},axis=1, inplace=True) OR
player.rename(columns={'points':'netpoints'}, inplace=True)
27) import pandas as pd
I=['Hydrogen','Helium','Lithium','Beryllium']
D1=['H','He','Li','Be']
D2=[1,2,3,4]
S1=pd.Series(D1,I)
print("First Series: ")
print(S1)
S2=pd.Series(D2,I)
print("Second Series: ")
print(S2)
D = {'Symbol': S1,'Atomic Number': S2}
DF=pd.DataFrame(D)
print("DataFrame:")
print(D F)
OR
import pandas as pd
D={'Symbol':['H','He','Li','Be'],'Atomic Number':[1,2,3,4]}
DF=pd.DataFrame(d,index=['Hydrogen', 'Helium','Lithium','Berillium'])
print(DF)
28.i)
I = DF[ DF['Diseasename'] == 'Tuberculosis' ].index
DF.drop(I, inplace = True) OR
DF.drop('Tuberculosis',axis=0) OR
DF=DF[(DF.diseasename!='Tuberculosis')]
ii) DF.loc[4]=['Malaria','Protozoa'] OR
DF.loc[4,:] = ['Malaria','Protozoa'] OR
DF = DF.append({'Diseasename':'Malaria','Agent': 'Protozoa'}, ignore_index=True)
(iii) print(DF.iloc[3:5]) OR
print(DF.tail(2)) OR
print(DF.iloc[-2::])
9. CBSE SAMPLE PAPER::2022.23
12. Which of the following can be used to specify
the data while creating a DataFrame?
i. Series ii. List of Dictionaries iii. Structured ndarray iv. All of these
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
i. Both A and R are true and R is the correct explanation for A
ii. Both A and R are true and R is not the correct explanation for A
iii. A is True but R is False
iv. A is false but R is True
18. Assertion (A):- DataFrame has both a row and column index.
Reasoning (R): - A DataFrame is a two-dimensional labelled data structure like a table of MySQL.
25. Carefully observe the following code:
import pandas as pd
Year1={'Q1':5000,'Q2':8000,'Q3':12000, 'Q4': 18000}
Year2={'A' :13000,'B':14000,'C':12000}
totSales={1:Year1,2:Year2}
df=pd.DataFrame(totSales)
print(df)
Answer the following:
i. List the index of the DataFrame df
ii. List the column names of DataFrame df.
XII – IP (2025.2026 Material & Old CBSE Questions) 94 2. DataFrames
27. Write a Python code to create a DataFrame with appropriate column headings from the list given below:
[ [101,'Gurman',98],[102,'Rajveer',95], [103,'Samar' ,96],[104,'Yuvraj',88] ]
28. Consider the given DataFrame ‘Stock’:
Name Price
0 Nancy Drew 150
1 Hardy boys 180
2 Diary of a wimpy kid 225
3 Harry Potter 500
Write suitable Python statements for the following:
i. Add a column called Special_Price with the following data: [135,150,200,440].
ii. Add a new book named ‘The Secret' having price 800.
iii. Remove the column Special_Price.
35. Mr. Som, a data analyst has designed the DataFrame df that contains data about Computer Olympiad with ‘CO1’,
‘CO2’, ‘CO3’, ‘CO4’, ‘CO5’ as indexes shown below.
Answer the following questions:
A. Predict the output of the following python statement: i. df.shape ii. df[2:4]
B. Write Python statement to display the data of Topper column of indexes CO2 to CO4.
OR (Option for part iii only)
Write Python statement to compute and display the difference of data of Tot_students column and First_Runnerup
column of the above given DataFrame.
CBSE SP::2022.23:: PYTHON::Answers
12. iv. All of these
18. i. Both A and R are true and R is the correct explanation for A
25. i. The index labels of df will include Q1, Q2, Q3, Q4, A, B, C
ii. The column names of df will be: 1,2
27. import pandas as pd #Statement 1
df=[["Divya","HR",95000], ["Mamta","Marketing",97000 ], ["Payal","IT",980000], ["Deepak","Sales",79000]]
#Statement 2
df=pd.DataFrame(df,columns=["Name","Department", "Salary"]) #Statement 3
print(df) #Statement 4
28. i. Stock['Special_Price']=[135,150,200,400]
ii. Stock.loc['4']=['The Secret',800]
iii. Stock=Stock.drop('Special_Price',axis=1)
35. A. Output:
i. (5,4)
ii. School tot_students Topper First_Runner_up
CO3 GPS 20 18 2
CO4 MPS 18 10 8
B. Python statement:
print(df.loc['CO2': 'CO4', 'Topper']) OR
print(df.Tot_students-df.First_Runnerup)
10. CBSE COMPARTMENT::2021.22
No Questions from DataFrames Concept
11. CBSE BOARD PAPER::2021.22
6. Which method is used to Delete row(s) from DataFrame?
a) .drop( ) method b) .del( ) method c) .remove( ) method d) .delete( ) method
9. Which of the following would give the same output as DF/DF1 where DF and DF1 are DataFrames.
a) DF.div(DF1) b)DF1.div(DF) c) Divide(DF,DF1) d) Div(DF,DF1)
10. Which of the following statement is wrong in context of DataFrame?
XII – IP (2025.2026 Material & Old CBSE Questions) 95 2. DataFrames
a) Two dimensional size is Mutable
b) Can perform Arithmetic operations on rows and columns.
c) Homogenous tabular data structure.
d) Create DataFrame from numpy ndarray.
11. Which attribute is not used with DataFrames.
a) size b) type c) empty d) columns
17. When we create a DataFrame from a list of Dictionaries, the columns labels are formed by the
a) Union of the keys of the dictionaries b) Intersection of the keys of the dictionaries
c) Union of the values of the dictionaries d) Intersection of the values of the dictionaries
19. Identify the correct option to select first four rows and second to fourth columns from a DataFrame ‘Data’.
a) display(Data.iloc[1:4,2:4]) b) display(Data.iloc[1:5,2:5])
c) print(Data.iloc[0:4,1:4]) d) print(Data.iloc[1:4,2:4])
29. Consider a following DataFrame:
import pandas as pd
s=pd.Series(data=[31,54,34,89,12,23])
df=pd.DataFrame(s)
Which statement will be used to get the output as 2?
a) print(df.index) b) print(df.shape( )) c) print(df.ndim) d) print(df.values)
30. Sandhya wants to display the last four rows of the dataframe df and she has written the following command:
df.tail( )
But the first 5 rows are being displayed. To rectify this problem, which of the following statements should be written.
a) df.head( ) b) df.last(4) c) df.tail(4) d) df.rows(4)
36. DataFrames can be created from?
a) Lists b) Dictionaries c) Series d) All of the above
38. Consider the following statements
Statement A: .loc( ) is a label based data selecting method to select a specific row(s) or column(s) which we want to
select.
Statement B: .loc( ) can not be used with default indices if customized indices are provided.
(a) Statement A is True but Statement B is False
(b) Statement A is False but Statement B is True
(c) Statement A and Statement B both are False
(d) Statement A and Statement B both are True
39. Abhay is a student of class ‘XII’, and he is aware of some concepts of python. He has created the DataFrame, but
he is getting errors after executing the code. Help him by identifying the correct statement that will create the
DataFrame:
Code:
import pandas as pd
stuname=[‘Muskan’,’Radhika’,’Gopar’,’Pihu’]
term1=[70,63,74,90]
term2=[67,70,86,95]
(a) df=pd.DataFrame({“Name”:stuname, ”marks1”:term1,”marks2”:term2})
(b) df=pd.dataframe([stuname,term1,term2], columns=[‘stuName’,”marks1”,”marks2”])
(c) df=pd.DataFrame({stuname,term1,term2})
(d) df=PD.dataframe({stuname,term1,term2})
41. Mr.Raman created a DataFrame from a Numpy array:
arr=np.array([[2,4,8],[3,9,27],[4,16,64]])
df=pd.DataFrame(arr,index=[‘one’,’two’,’three’],___)
print(df)
Help him to add a customized column labels to the above DataFrame
(a) columns=’no’,’sq’,’cube’
(b) column=[‘no’,’sq’,’cube’]
(c) columns=[‘no’,’sq’,’cube’]
(d) columns=[[‘no’,’sq’,’cube’]]
42. What will be the output of the following program:
import pandas as pd
dic={‘Name’:[‘Sapna’,’Anmol’,’Rishul’,’Sameep’], Agg’:[56,67,75,76],’Age’:[16,18,16,19])
df=pd.DataFrame(dic,columns=[‘Name’,’Age’])
print(df)
XII – IP (2025.2026 Material & Old CBSE Questions) 96 2. DataFrames
(a) (b) (c) (d)
Name Agg Age Name Agg Age Name Name Age
101 Sapna 56 16 0 Sapna 56 16 0 Sapna 0 Sapna 16
102 Anmol 67 18 1 Anmol 67 18 1 Anmol 1 Anmol 18
103 Rishul 75 16 2 Rishul 75 16 2Rishul 2 Rishul 16
104 Sameep76 19 3 Sameep 76 19 3 Sameep 3 Sameep 19
43. Consider the following code:
import pandas as pd
S1=pd.Series([23,24,35,56],index=[‘a’,’b’,’c’,’d’])
S2=pd.Series([27,12,14,15],index=[‘b’,’y’,’c’,’ab’])
df=pd.DataFrame(S1+S2)
print(df)
Output for the above code will be:
(a) (b) (c) (d)
0 0 0 0
a NaN a 50 b 50 a NaN
ab NaN b 36 y 36 ab NaN
b 51.0 c 49 c 49 b NaN
c 49.0 d 71 ab 71 c NaN
d NaN d NaN
y NaN y NaN
44. Sudhanshu has written the following code to create a DataFrame with Boolean index:
import numpy as np
import pandas as pd
df=pd.DataFrame(data=[[5,6,7]],index=[true,false,true])
print(df)
While executing the code, she is getting an error, help her to rectify the code:
(a) df=pd.DataFrame([True,False,True],data=[5,6,7])
(b) df=pd.DataFrame(data=[5,6,7], index=[True,False,True])
(c) df=pd.DataFrame([true,false,true],data=[5,6,7])
(d) df=pd.DataFrame(index=[true,false,true],data=[[5,6,7]])
49. Sushila has created a DataFrame with the help of the following code:
import pandas
EMP={‘EMPID’:[‘E01’,’E02’,’E03’,’E04’,’E05’],’EMPNAME’:[‘KISHORI’,’PRIYA’,’DAMODAR’,’REEMA’,’M
ANOJ’], ’EMP_SALARY’: [67000,34000,68000,90000,43000]}
df=pandas.DataFrame(EMP, index=[‘001’,’002’,’003’,’004’,’005’])
print(df.loc[0:3, :])
and she wants to get the following output:
EMPID EMPNAME EMP_SALARY
001 E01 KISHORI 67000
002 E02 PRIYA 34000
003 E03 DAMODAR 68000
Help her to correct the code
(a) print(df.iloc[‘001’:’003’, : ]) (b) print(df.loc[‘001’:’003’, : ])
(c) print(EMP[loc[0:3,: ]]) (d) print(df.loc[‘001’:’004’,: ])
SECTION-C
Section C consists of 6 questions (50-55). Attempt any five questions.
Case Study
Ms Ramdeep kaur maintains the records of all students of her class. She wants to perform some operations on the data:
Code:
import pandas as pd
t={‘Rollno’:[101,102,103,104,105,106,107], ‘Name’:[Shubrato’’Krishna’,’Pranshu’,’Gurpreet’,
’Arpit’,’Sanidhya’,’Aruobindo’], ’Age’:[15,14,14,15,16,15,16],
’Marks’:[77.9,70.4,60.9,80.3,86.5,67.7,85.0], ’Grade’: [‘11B’,’11A’,’11B’,’11C’,’11E’,’11A’,’11C’]}
df=pd.DataFrame(t,index=[10,20,30,40,50,60,70])
print(df)
Output of the above code:
Rollno Name Age Marks Grade
10 101 Shubrato 15 79.9 11B
20 102 Krishna 14 70.4 11A
XII – IP (2025.2026 Material & Old CBSE Questions) 97 2. DataFrames
30 103 Pranshu 14 60.9 11B
40 104 Gurpreet 15 80.3 11C
50 105 Arpit 16 86.5 11E
60 106 Sanidhya 15 67.7 11A
70 107 Aurobindo 16 85.0 11C
Based on the given information, answer questions No.50-55.
50. Select the correct statement for the below output:
Name Krishna
Age 14
Marks 70.4
Grade 11A
Name:20, dtype:object
(a) print(df.iloc[2]) (b) print(df.loc[2]) (c) print(df.iloc[20]) (d) print(df.loc[20])
51. The teacher wants to know the marks secured by the second last student only. Which statement would help
her to get the correct answer?
(a) print(df.loc[60:70,’Marks’]) (b) print(df.loc[60:60,’Marks’])
(c) print(df.iloc[-2:-2],[‘Marks’]) (d) print(df[-2:-2][‘Marks’])
52. Which of the following statement(s) will add a new column ‘fee’ at second position with values
[3200,3400,4500,3100,3200,4000,3700]in DataFrame df?
(a) df.insert(loc=2,column=’fee’, value= [3200,3400,4500,3100,3200,4000,3700])
(b) df.add(2,column=’fee’, [3200,3400,4500,3100,3200,4000,3700])
(c) df.append(loc=2,’ fee’ =[3200,3400,4500,3100,3200,4000,3700])
(d) df.insert(loc=2,’fee’, [3200,3400,4500,3100,3200,4000,3700])
53. Which of the following commands is used to delete the column ‘Grade’ in the DataFrame df?
(a) df.drop(‘Grade’,axis=1,inplace=True) (b) df.drop(‘Grade’,axis=0,inplace=True)
(c) df.drop[‘Grade’,axis=1,inplace=True] (d) df.delete(‘Grade’,axis=1,inplace=True)
54. Which of the following commands would rename the column ‘Marks’ to ‘Halfyearly’ in the DataFrame df?
(a) df.rename([‘Marks’,’Halfyearly’],inplace=True)
(b) df.rename({‘Marks’,’Halfyearly’},inplace=True)
(c) df.rename(columns={‘Marks’:’Halfyearly’}, inplace=True)
(d) df.rename([‘Marks’:’Halfyearly’],inplace=True)
55. Which of the following commands will display the Names and Marks of a students getting more than 80
marks?
(a) print(df.loc[‘Marks’>80,[‘Name’,’Marks’]]) (b) print(df.loc[df[‘Marks’]<80,’Name’,’Marks’])
(c) print(df.loc[df[‘Marks’]<80,[‘Name’,’Marks’]]) (d) print(df.loc[df[‘Marks’]>80,[‘Name’,’Marks’]])
CBSE QP::2021.22:: PYTHON(T1)::Answers
6.a 9a 10c 11b 17a
19c 29c 30c 36d 38a
39a 41c 42d 43a 44b
49b 50d 51b 52a 53a
54c 55d
12. CBSE SAMPLE PAPER :: 2021.22
9. Method or function to add a new row in a data frame is: a. .loc() b. .iloc() c. join d. add()
17. While accessing the column from the data frame, we can specify the column name. In case column does not exist,
which type of error it will raise:
a. Key Error b. Syntax Error c. Name Error d. Runtime Error
19. Function to display the first n rows in the DataFrame:
a. tail (n) b. head (n) c. top (n) d. first (n)
23. Pandas data frame cannot be created using:
a. Dictionary of tuples b. Series c. Dictionary of List d. List of Dictionaries
25. Which of the following is not an attribute of pandas data frame?
a. length b. T c. Size d. shape
37. What is a correct syntax to return the values of first row of a Pandas DataFrame? Assuming the name of the
DataFrame is dfRent.
a. dfRent[0] b. dfRent.loc[1] c. dfRent.loc[0] d. dfRent.iloc[1]
XII – IP (2025.2026 Material & Old CBSE Questions) 98 2. DataFrames
39. Difference between loc() and iloc().:
a. Both are Label indexed based functions.
b. Both are Integer position-based functions.
c. loc() is label based function and iloc() integer position based function.
d. loc() is integer position based function and iloc() index position based function.
42. Which command will be used to delete 3 and 5 rows of the data frame. Assuming the data frame name as DF.
a. DF.drop([2,4],axis=0) b.DF.drop([2,4],axis=1)
c. DF.drop([3,5],axis=1) d. DF.drop([3,5])
44. Ritika is a new learner for the python pandas, and she is aware of some concepts of python. She has created some lists, but is
unable to create the data frame from the same. Help her by identifying the statement which will create the data frame.
import pandas as pd
Name=['Manpreet','Kavil','Manu','Ria']
Phy=[70,60,76,89]
Chem=[30,70,50,65]
a.df=pd.DataFrame({"Name":Name,"Phy":Phy, "Chem":Chem})
b. d=("Name":Name,"Phy":Phy,"Chem":Chem)
df=pd.DataFrame(d)
c. df=pd.DataFrame([Name,Phy,Chem], columns=['Name', "Phy","Chem","Total"])
d. df=pd.DataFrame({Name:"Name", Phy :"Phy", Chem: "Chem"})
46. Assuming the given structure, which command will give us the given output:
Output Required: (3,5)
a. print(df.shape()) b. print(df.shape) c. print(df.size) d. print(df.size())
47. Write the output of the given command: df1.loc[:0,'Sal']
Consider the given dataframe.
a. 0 Kavita 50000 3000 b. 50000 c. 3000 d. 50000
48. Consider the following data frame name df
Write the output of the given command: print(df.marks/2)
a 0 45.0
1 NaN
2 43.5
Name: Marks, dtype:float64
b 0 45.0
1 NaN
2 43
Name: Marks, dtype:float64
c 0 45
1 NaN
2 43.5
Name: Marks, dtype:float64
d 0 45.0
1 0
2 43.5
Name: Marks, dtype:float64
XII – IP (2025.2026 Material & Old CBSE Questions) 99 2. DataFrames
49. Read the statements given below. Identify the right option from the following for Attribute and method/function.
Statement A: Attribute always ends without parenthesis.
Statement B: Function/Method cannot work without arguments.
a. Both statements are correct.
b. Both statements are incorrect.
c. Statement A is correct, but Statement B is incorrect
d. Statement A is incorrect, but Statement B is correct
Case Study Questions
Mr. Sharma is working with an IT company, and he has provided some data. On which he wants to do some operations,
but he is facing some problem, help him:
Code:
import pandas as pd
ResultSheet={'Naveen': pd.Series([90, 91, 97], index=['Maths','Science','Hindi']),
'Rehana': pd.Series([92, 81, 96], index=['Maths','Science','Hindi']),
'John': pd.Series([89, 91, 88], index=['Maths','Science','Hindi']),
'Roja': pd.Series([81, 71, 67], index=['Maths','Science','Hindi']),
'Mannat': pd.Series([94, 95, 99], index=['Maths','Science','Hindi'])}
DF = pd.DataFrame(ResultSheet)
print(DF)
Output of the above code:
Based on the given information, answer the questions NO. 50-55.
50. He wants to add a new column with name of student ‘Prem’ in above data frame choose the right command to do
so:
a. DF['Prem']=[89,78,76] b. df['Prem']=[89,78,76]
c. DF['Prem']=[89,78,76,67] d. DF['Name']=[89,78,76]
51. He wants to set all the values to zero in data frame, choose the right command to do so:
a. DF=0 b. DF[]=0 c. DF[:]=0 d. F[:]==0
52.He wants to delete the row of science marks:
a. DF.drop('Science', axis=1) b. DF.drop('Science', axis=0)
c. DF.drop('Science', axis=-1) d. DF.drop('Science', axis= =0)
53. The following code is to create another data frame, which he wants to add to the existing Data frame. Choose the
right command to do so:
Sheet1={ 'Aaradhya': pd.Series([90, 91, 97], index=['Maths','Science','Hindi'])}
S1=pd.DataFrame(Sheet1)
a. DF.append(S1,axis=0) b. DF.append(S1) c. DF.insert(S1) d. DF.join(S1)
54. What will be the output of the given command? DF.index=['A','B','C']
a.
b.
c.
XII – IP (2025.2026 Material & Old CBSE Questions) 100 2. DataFrames
d. Error, Index already exists and cannot be overwritten.
55. What will be the output of the given command?
print(DF.size)
a. 15 b. 18 c. 21 d. 23
CBSE SP::2021.22:: PYTHON(T1)::Answers
9. a. loc()
17. a. Key Error
19. b. head (n)
23. a. dictionary of tuples
25. a. length
37. c. dfRent.loc[0]
39. c. loc() is label based function and iloc( ) integer position based function.
42. aDF.drop([2,4],axis=0)
44. a.
46. b. print(df.shape)
47. b. 50000
48. a.
49. c. Statement A is correct, but Statement B is
incorrect
50. a. DF['Prem']=[89,78,76]
51. c DF[:]=0
52. b. DF.drop('Science', axis=0)
53. b. DF.append(S1)
54. b.
55. a. 15
13.CBSE COMPARTMENT 2021
13. What will be the output of the Python program ?
import pandas as pd
I=['Apple','Banana','Mango','Orange','Litchi']
df=pd.DataFrame(I,index=[1,2,3,4,5])
print(df.iloc[1:3])
22. Case Based Study Question
Consider the following DataFarme df and answer any four questions from (i) to (v) :
import pandas as pd
t={'rollno':[1,2,3,4,5,6], 'Name':['Krishna','Pranshu','Gurusha','Arpit','Rani', 'Aurobindo'], 'Age':[15,14,14,15,16,15],
'marks':[70.4,60.9,80.3,87.5,67.8,86.0], 'class':['11A','12B','11B','12B','12B','11B']
}
df = pd.DataFrame(t,index=[10,20,30,40,50,60])
i) Write down the command that will give the following output :
rollno 2
Name Pranshu
Age 14
Marks 60.9
Class 12B
Name: 20, dtype: object
(A) print(df.iloc[1]) (B) print(df.loc[1]) (C) print(df.LOC[1]) (D) print(df.iloc(1))
ii) The teacher wants to know the highest marks secured by the students. Which statement
would help her to get the correct answer ?
(A) print(df[marks].max()) (B) print(df.max([marks]))
(C) print(df['marks'].max()) (D) print(df('marks').max)
iii) Which of the following statement(s) will add new column ‘fee’ as third column with values
[3200,3400,4500,3100,3200,4000] in DataFrame df ?
XII – IP (2025.2026 Material & Old CBSE Questions) 101 2. DataFrames
(A) df.insert(loc=2,column='fee',value=[3200,3400,4500,3100,3200,4000])
(B) df.add(2,column='fee', [3200,3400,4500,3100,3200,4000])
(C) df.append(loc=2, 'fee'=[3200,3400,4500,3100,3200,4000])
(D) df.insert(loc=2, 'fee'=[3200,3400,4500,3100,3200,4000])
iv) Which of the following commands is useds to remove the column ‘Age’ in the DataFrame df?
(A) df.drop('Age',axis=1,inplace=True) (B) df.drop('Age',axis=0,inplace=True)
(C) df.drop['Age',axis=1,inplace=True] (D) df.delete('Age',axis=1,inplace=True)
v) Which of the following command would rename the DataFrame df ?
(A) df.rename(['marks','Term1'],inplace=True)
(B) df.rename({'marks':'Term1'},inplace=True)
(C) df.rename(columns={'marks':'Term1'},inplace=True)
(D) df.rename(['marks':'Term1'],inplace=True)
30. Consider the following dataFrame ‘stu’ :
Write the statements for the DatFrame “stu” :
(i) Display the details of the students in the reverse order of their indexes.
(ii) Add a new row in the DataFrame “stu” with values (1006, Sujal, Sharma, 17, 87, 89)
38(a) Write a program in Python Pandas to create the following DataFrame “population” from a Dictionary:
(b) Perform the following operations on the DataFrame:
(i) Display the columns country and population.
(ii) Display all the rows where population is more than
40. (iii) Delete the last 2 rows.
CBSE COMPARTMENT ::2021::ANSWERS
13. 0
2 Banana
3 Mango
22.i) (A) print(df.iloc[1])
ii) (C) print(df['marks'].max())
iii) (A) df.insert(loc=2,column='fee', value=[3200,3400,4500,3100,3200,4000])
iv) (A) df.drop('Age',axis=1,inplace=True)
v) (C) df.rename(columns={'marks':'Term1'}, inplace=True)
30.i) print(stu[::-1])
ii) stu=stu.append({'Admno':1006, 'Firstname':'Sujal','Lastname':'Sharma','Age':17, 'Pretest': 87,'Posttest': 89},
ignore_index=True) OR
stu.loc[5]=[1006, Sujal, Sharma, 17, 87, 89] OR
stu.loc[len(stu.index)]=[1006, Sujal, Sharma, 17, 87, 89] OR
stu.at[5]=[1006, Sujal, Sharma, 17, 87, 89]
38.a)
import pandas as pd
IDX=['IT','ES','GR','FR','PO']
D= {'country':['Italy','Spain','Greece','France','Portugal'], 'population':[61,46,11,65,10],
'percent':[0.83,0.63,0.15,0.88,0.14] }
DF=pd.DataFrame(D,index=IDX)
XII – IP (2025.2026 Material & Old CBSE Questions) 102 2. DataFrames
b) (i) print(DF[['country','population']])
(ii) print(DF[DF.population>40]) OR
print(DF[DF['population']>40])
(iii) DF.drop(DF.tail(2).index,inplace=True) OR
DF=DF.drop(axis=0,labels=['FR','PO']) OR
DF=DF.drop(['FR','PO']) OR
DF.drop(DF.index[[3,4]], inplace=True)
14.CBSE SAMPLE PAPER ::2020.21
8. In a DataFrame, Axis= 1 represents the_____________ elements.
13. In Pandas the function used to check for null values in a DataFrame is ________
22. Consider the following DataFramedfand answer any four questions from (i)-(v)
(i) Write down the command that will give the following output.
a. print(df.max) b. print(df.max()) c. print(df.max(axis=1)) d. print(df.max, axis=1)
(ii) The teacher needs to know the marks scored by the student with roll number 4. Help her to identify the correct set
of statement/s from the given options:
a. df1=df[df[‘rollno’]= =4]
print(df1)
b. df1=df[rollno= =4]
print(df1)
c. df1=df[df.rollno=4]
print(df1)
d. df1=df[df.rollno= =4]
print(df1)
(iii) Which of the following statement/s will give the exact number of values in each column of the dataframe?
i. print(df.count()) ii. print(df.count(0)) iii.print(df.count) iv. print(df.count(axis=’index’))
Choose the correct option:
a. both (i) and (ii) b. only (ii) c. (i), (ii) and (iii) d. (i), (ii) and (iv)
(iv) Which of the following command will display the column labels of the DataFrame?
a. print(df.columns()) b. print(df.column()) c. print(df.column) d. print(df.columns)
(v) Ms. Sharma, the class teacher wants to add a new column, the scores of Grade with the values,
‘ A’, ‘B’, ‘A’, ‘A’, ‘B’, ‘A’ , to the DataFrame.
Help her choose the command to do so:
a. df.column=[’A’,’B’,’A’,’A’,’B’,’A’] b. df [‘Grade’]=[’A’,’B’,’A’,’A’,’B’,’A’]
c. df.loc[‘Grade’]= [’A’,’B’,’A’,’A’,’B’,’A’] d. Both (b) and (c) are correct
30. Consider the following DataFrame, classframe
Write commands to : i. Add a new column ‘Activity’ to the Dataframe
ii. Add a new row with values ( 5 , Mridula ,X, F , 9.8, Science)
XII – IP (2025.2026 Material & Old CBSE Questions) 103 2. DataFrames
38. Write a program in Python Pandas to create the following DataFrame batsman from a Dictionary:
Perform the following operations on the DataFrame :
1) Add both the scores of a batsman and assign to column “Total”
2) Display the highest score in both Score1 and Score2 of the DataFrame.
3) Display the DataFrame
CBSE SP::2020.21:: PYTHON::Answers
8. column
13. isnull( )
22.i) b. print(df.max())
ii) a. df1=df[df[‘rollno’]==4]
print(df1)
d. df1=df[df.rollno==4]
print(df1)
iii) a. both (i) and (ii)
iv) a. d. print(df.columns)
v) b. df [‘Grade’]=[’A’,’B’,’A’,’A’,’B’,’A’]
30. i.classframe[‘Activity’]=[‘Swimming’, ’Dancing’,’Cricket’, ‘Singing’]
ii. classframe.loc[‘St5’]=[1, ’Mridula’, ‘X’, ‘F’, 9.8, ‘Science’]
38. import pandas as pd
d1={'B_NO':[1,2,3,4], 'Name':["Sunil Pillai","Gaurav Sharma", "Piyush Goel","Kartik Thakur"],
'Score1':[90,65,70,80], 'Score2':[80,45,95,76] }
df=pd.DataFrame(d1)
print(df)
df['Total'] = df['Score1']+ df['Score2']
Alternative Answer
Scheme
df['Total'] = sum(df['Score1'], df['Score2'])
print(df)
print("Maximum scores are : " , max(df['Score1']), max(df['Score2']))
15.CBSE COMPARTMENT 2020
2.b) Write the correct output on execution of the following Pandas code:
import pandas as pd
df=pd.DataFrame([("Om",93),("Jay",91)], columns=['Name','Mark'])
print(df.sort_values('Name', ascending=True))
2.f) Write the correct output on execution of the following Pandas code:
import pandas as pd
df = pd.DataFrame({"A": ["P01", "P02","P03"], "B": ["Pen", "Pencil", "Eraser"]})
df=df.rename(columns={"A": "PID", "B": "PNAME"})
df=df.rename(index={0: 'A', 1: 'B', 2: 'C'})
print(df)
2.h) Consider the following dataframe “df”
write single line statements for each of the following parts (a) to (d), which use Pandas method:
a. To display the 'Names' and 'Marks' columns from the DataFrame.
b. to change the 'Marks' in the 4th row (i.e. for index 3) to 91.5
c. to display the rows where number of 'Trials' in the examination is less than 2 and 'Marks' is greater than 95
d. to sort the DataFrame in descending order of 'Marks'
CBSE COMPARTMENT :: 2020::ANSWERS
2.b) Name Mark
1 Jay 91
0 Om 93
XII – IP (2025.2026 Material & Old CBSE Questions) 104 2. DataFrames
2f) PID PNAME
A P01 Pen
B P02 Pencil
C P03 Eraser
2h) a. print(df[['Names', 'Marks']])
b. df.loc[3, 'Marks'] = 91.5
c. print(df[(df['Trials'] < 2) & (df['Marks'] > 95)])
d. df.sort_values(by=['Marks'], ascending=[False], inplace=True)
16.CBSE SAMPLE PAPER :: 2019.20
1.c) Write a suitable Python code to create an empty dataframe.
OR
Consider the following dataframe : student_df
Name class marks
Anamay XI 95
Aditi XI 82
Mehak XI 65
Kriti XI 45
Write a statement to get the minimum value of the
column marks.
2.b) Hitesh wants to display the last four rows of the data frame df and has written the following code: df.tail()
But last 5 rows are being displayed. Identify the error and rewrite the correct code so that last 4 rows get displayed.
OR
A dataframe studdf stores data about the students stream, marks. A part of it is shown below:
Class Stream Marks
11 Science 95
11 Commerce 80
11 Arts 75
11 Vocational 65
Using the above dataframe, write the command to compute Average marks stream wise.
2.d) Write a small python code to drop a row from dataframe labeled as 0.
2.f) Write a python code to create a dataframe with appropriate headings from the list given below :
['S101', 'Amy', 70], ['S102', 'Bandhi', 69], ['S104', 'Cathy', 75], ['S105', 'Gundaho', 82]
OR
Write a small python code to create a dataframe with headings(a and b) from the list given below :
[[1,2],[3,4],[5,6],[7,8]]
2.g) Consider the following dataframe, and answer the questions given below:
import pandas as pd
df = pd.DataFrame({“Quarter1":[2000, 4000, 5000, 4400,10000], "Quarter2":[5800, 2500, 5400, 3000, 2900],
"Quarter3":[20000, 16000, 7000, 3600, 8200], "Quarter4":[1400, 3700, 1700, 2000, 6000]})
(i) Write the code to find mean value from above dataframe df over the index and column axis.
(ii) Use sum() function to find the sum of all the values over the index axis.
(iii) Find the median of the dataframe df.
OR
Given a data frame df1 as shown below:
City Maxtemp MinTemp RainFall
Delhi 40 32 24.1
Bengaluru 31 25 36.2
Chennai 35 27 40.8
Mumbai 29 21 35.2
Kolkata 39 23 41.8
(i) Write command to compute sum of every column of the data frame.
(ii) Write command to compute mean of column Rainfall.
(iii) Write command to compute Median of the Maxtemp Column.
2.h) Find the output of the following code:
import pandas as pd
data = [{'a': 10, 'b': 20},{'a': 6, 'b': 32, 'c': 22}]
#with two column indices, values same as dictionary keys
XII – IP (2025.2026 Material & Old CBSE Questions) 105 2. DataFrames
df1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])
#With two column indices with one index with other name
df2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])
print(df1)
print(df2)
2.i) Write the code in pandas to create the following dataframes :
df1 df2
mark1 mark2 mark1 mark2
0 10 15 0 30 20
1 40 45 1 20 25
2 15 30 2 20 30
3 40 70 3 50 30
Write the commands to do the following operations on the dataframes given above :
(i) To add dataframes df1 and df2.
(ii) To subtract df2 from df1
(iii) To rename column mark1 as marks1in both the dataframes df1 and df2.
(iv) To change index label of df1 from 0 to zero and from 1 to one.
CBSE SP::2019..20:: PYTHON::Answers
1.c) import pandas as pd
df=pd.DataFrame()
print(df)
OR
Student_df[‘marks’.min( )]
2.b) df.tail (4)
OR
Studdf.pivot_table(index=’Stream’
Values=’marks’, aggfunc=’mean’)
2.d) # Drop rows with label 0
df = df.drop(0)
print(df )
2.f) import pandas as pd
# initialize list of lists
data = [['S101', 'Amy', 70], ['S102', 'Bandhi', 69], ['S104', 'Cathy', 75], ['S105', 'Gundaho', 82]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['ID', 'Name', 'Marks'])
# printdataframe.
print(df )
OR
import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])
df = df.append(df2)
2.h) a b
first 10 20
second 6 32
a b1
first 10 NaN
second 6 NaN
2 i)
import numpy as np
import pandas as pd
df1 = pd.DataFrame({'mark1':[30,40,15,40], 'mark2':[20,45,30,70]});
df2 = pd.DataFrame({'mark1':[10,20,20,50], 'mark2':[15,25,30,30]});
print(df1)
print(df2)
(i) print(df1.add(df2))
(ii) print(df1.subtract(df2))
(iii) df1.rename(columns={'mark1':'marks1'}, inplace=True)
print(df1)
(iv) df1.rename(index = {0: "zero", 1:"one"}, inplace=True)
print(df1)
XII – IP (2025.2026 Material & Old CBSE Questions) 106 2. DataFrames
CBSE – QUESTION BANK QUESTIONS
Q.1. Mr. Ankit is working in an organisation as data analyst. He uses Python Pandas and Matplotlib for the
same. He got a dataset of the passengers for the year 2010 to 2012 for January, March and December. His
manager wants certain information from him, but he is facing some problems.
Help him by answering few questions given below:
Code to create the above data frame:
import pandas as ____________ #Statement 1
data={"Year":[2010,2010,2012,2010,2012], "Month":["Jan","Mar","Jan","Dec","Dec"],
"Passengers":[25,50,35,55,65]}
df=pd._____________(data) #Statement 2
print(df)
i. Choose the right code from the following for statement 1.
i. pd ii. df iii. Data iv. p
ii. Choose the right code from the following for the statement 2.
i. Dataframe ii. DataFrame iii. Series iv. Dictionary
iii. Choose the correct statement/ method for the required output: (5,3)
i. df.index ii. df.shape() iii. df.shape iv. df.size
iv. He wants to print the details of "January" month along with the number of passengers,
Identify the correct statement:
i. df.loc[['Month','Passengers']][df['Month']=='Jan']
ii. df[['Month','Passengers']][df['Month']=='Jan']
iii. df.iloc[['Month','Passengers']][df['Month']=='Jan']
iv. df(['Month','Passengers']][df['Month']=='Jan')
v. Mr. Ankit wants to change the index of the Data Frame and the output for the same is given below. Identify the
correct statement to change the index.
i. df.index[]=["Air India", "Indigo", "Spicejet", "Jet","Emirates"]
ii. df.index["Air India","Indigo","Spicejet", "Jet","Emirates"]
iii. df.index=["Air India","Indigo","Spicejet", "Jet","Emirates"]
iv. df.index()=["Air India","Indigo","Spicejet", "Jet","Emirates"]
Answers
(i) (i) pd
(ii) (ii) DataFrame
(iii) (iii) df.shape
(iv) (ii) df[['Month','Passengers']][df['Month']=='Jan']
(v) (iii) df.index=["Air India","Indigo","Spicejet","Jet","Emirates"]
XII – IP (2025.2026 Material & Old CBSE Questions) 107 2. DataFrames
9. Sanyukta is the event incharge in a school. One of her students gave her a suggestion to use Python Pandas
and Matplotlib for analysing and visualising the data, respectively. She has created a Data frame “SportsDay”
to keep track of the number of First, Second and Third prizes won by different houses in various events.
Write Python commands to do the following:
i. Display the house names where the number of Second Prizes are in the range of 12 to 20.
a. df['Name'][(df['Second']>=12) and (df['Second']<=20)]
b. df[Name][(df['Second']>=12) & (df['Second']<=20)]
c. df['Name'][(df['Second']>=12) & (df['Second']<=20)]
d. df[(df['Second']>=12) & (df['Second']<=20)]
ii. Display all the records in the reverse order.
a. print(df[::1]) b. print(df.iloc[::-1])
c. print(df[-1:]+df[:-1]) d. print(df.reverse())
iii. Display the bottom 3 records.
a. df.last(3) b. df.bottom(3) c. df.next(3) d. df.tail(3)
iv. Choose the correct output for the given statements:
x=df.columns[:1]
print(x)
a. 0 b. Name c. First d. Error
v. Which command will give the output 24:
a. print(df.size) b. print(df.shape) c. print(df.index) d. print(df.axes)
Answers
i. c ii. b iii.d iv. b v. a
Q.18. Zeenat has created the following data frame dataframe1 to keep track of data Rollno, Name, Marks1 and Marks2
for various students of her class where row indexes are taken as the default values:
i. Which among the following option will give 90, 95 as output
a) print(max(dataframe1['Marks1','Marks2'])
b)print((dataframe1.Marks1.max(), dataframe1.Marks2.max())))
c) print(max(dataframe1['Marks1'])
d) print(max(dataframe1['Marks2'])
ii. She needs to know the marks scored by Rollno 2. Help her to identify the correct set of statement/s
from the given options:
a. print(dataframe1[dataframe1['Rollno']= =2]) b. print(dataframe1['Rollno']= =2)
c. print(dataframe1[dataframe1. Rollno = =2]) d. print(dataframe1[dataframe1['Rollno']])
iii. Which of the following statement/s will delete the 3rd column?
a. del dataframe1['Marks1'] b. dataframe1.pop('Marks1')
c. drop dataframe1['Marks1'] d. pop dataframe1['Marks1']
Choose the correct option:
a) both (a) and (b) b) only (b)
c) (a), (b) and (c) d) (a), (b) and (d)
iv. Which of the following command will display the total number of elements in the dataframe?
a. print(dataframe1.shape) b. print(dataframe1.num)
c. print(dataframe1.size) d. print(dataframe1.elements)
XII – IP (2025.2026 Material & Old CBSE Questions) 108 2. DataFrames
v. Now she wants to add a new column Marks3 with relevant data. Help her choose the command to
perform this task.
a. dataframe1.column=[ 45,52,90,95] b. dataframe1 ['Marks3']= [ 45,52,90,95]
c. dataframe1.loc['Marks3']= [ 45,52,90,95] d. Both (b) and (c) are correct
Answers
i. b ii. C iii. (a) - both (a) and (b)
iv. C v. b
19. Naman has created the following dataframe “Climate” to record the data about climatic conditions of four
years.
i. Which of the following code snippets will return the MaxTemp and Rainfall for year 2018 and
2019?
a. Climate[['MaxTemp','Rainfall']][1:3] b. Climate['MaxTemp', 'Rainfall'][1:3]
c. Climate.iloc[1:3] d. Climate.iloc[1:3,1:2]
ii. Display the temperature difference between MaxTemp and MinTemp for all the rows in the
dataframe Climate.
a. Climate=Climate["MaxTemp"]-Climate["MinTemp"] b. print(Climate["maxt"]-Climate["mint"])
c. print(Climate["MaxTemp"]-Climate["MinTemp"]) d. print(Climate.Climate["MaxTemp"]-Climate["MinTemp"])
iii. To display 2 rows from the top in the dataframe, which of the following statement is correct:
a. print (Climate.head()=2 ) b. print (Climate.head(n==2) )
c. print (Climate.head(range(2)) ) d. print (Climate.head(2) )
iv. Which of the following statement/s will give the exact number of values in each column of the
dataframe?
a. print(Climate.count()) b. print(Climate.count(0))
c. print(Climate.count) d. print(Climate.count(axis='index'))
Choose the correct option:
a) both (a) and (b) b) only (b)
c) (a), (b) and (c) d) (a), (b) and (d)
v. To display 2 rows from the bottom in the dataframe, which of the following statement is correct:
a. print (Climate.tail()=2 ) b. print (Climate.tail(n==2) )
c. print(Climate.tail(range(2))) d. print (Climate.tail(2) )
Answers
i. c ii. C iii. d iv. d) - (a), (b) and (d) v. d
21. HR Department of ABCTech has created following dataframe to store data about salaries and bonus paid to
their employees:
import pandas as pd
import numpy as np
d1={'EName':[ 'Kavita', 'Sudha','Garima’]'], 'Sal': [50000,60000,55000],'Bonus':[3000,4000,5000]}
Df1=pd.DataFrame(d1)
Choose the python statement using suitable functions for the following tasks:
i. Display the columns Sal and Bonus
a. df1 [:Sal :Bonus] b. df1.loc(['Sal','Bonus'])
c. df1.iloc(['Sal','Bonus']) d.df1[['Sal','Bonus']]
ii. Display the details of employee Kavita.
a. df1[df1.EName='Kavita'] b. df1.loc[df1.EName=='Kavita']
c. df1.iloc[df1.EName=='Kavita'] d. df1[EName='Kavita']
iii. Display the details of the last employee.
a. Df1.tail(1) b. Df1.tail (-1) c. Df1.head(n=1) d. Df1.head()
iv. Add a new column named ‘Email’ with the value “abc@gmail.com”.
a. Df1[‘Email’]= ‘abc@gmail.com’ b. Df1[Email]=’abc@gmail.com’
c. Df1.loc[‘Email’]=’abc@gmail.com’ d. Df1(‘Email’)=’abc@gmail.com’
v. Write a python statement to print the details of employees having Sal more than 50000
a. df1.Sal>=5000 b. df1[df1.Sal>=5000] c. df1[df1.'Sal'>=5000] d.df1.iloc[df1.Sal>=5000]
Answers : i. b ii. b iii. a iv. a v. b
XII – IP (2025.2026 Material & Old CBSE Questions) 109 2. DataFrames
Assertion and Reasoning Questions
1. Assertion (A):- While creating a dataframe with a nested or 2D dictionary, Python interprets the outer dict keys as
the columns and the inner keys as the row indices.
Reasoning (R):- A column can be deleted using the remove command.
Ans.: c) A is true but R is False
Explanation: To delete a column drop() or del can be used.
2. Assertion (A): DataFrame has both a row and column index.
Reasoning (R): .loc() is a label-based data selecting method to select a specific row(s) or column(s) that we want to
select.
Ans.: a) Both A abd R are True and R is correct explanation of A
3. Assertion (A): – When DataFrame is created by using Dictionary, keys of dictionary are set as columns of
DataFrame.
Reasoning (R):- Boolean Indexing helps us to select the data from the DataFrames using a boolean vector.
Ans.: b) Both A and R are true but R is not correct explanation of A
4. Assertion (A):- DataFrame has both a row and column index.
Reasoning (R): – A DataFrame is a two-dimensional labeled data structure like a table of MySQL.
Ans.: a) Both A and R are true and R is correct explanation of A
NCERT SUMMARY
(SERIES & DATAFRAMES)
❖ A DataFrame is a two-dimensional labeled data structure like a spreadsheet. It contains rows and columns and
therefore has both a row and column index.
❖ When using a dictionary to create a DataFrame, keys of the Dictionary become the column labels of the DataFrame.
A DataFrame can be thought of as a dictionary of lists/ Series (all Series/columns sharing the same index label for a
row).
❖ Data can be loaded in a DataFrame from a file on the disk by using Pandas read_csv function.
❖ Data in a DataFrame can be written to a text file on disk by using the pandas.DataFrame.to_csv() function.
❖ DataFrame.T gives the transpose of a DataFrame.
❖ Pandas haves a number of methods that support label based indexing but every label asked for must be in the index,
or a KeyError will be raised.
❖ DataFrame.loc[ ] is used for label based indexing of rows in DataFrames.
❖ Pandas.DataFrame.append() method is used to merge two DataFrames.
❖ Pandas supports non-unique index values. Only if a particular operation that does not support duplicate index values
is attempted, an exception is raised at that time.
❖ The basic difference between Pandas Series and NumPy ndarray is that operations between Series automatically
align the data based on labels. Thus, we can write computations without considering whether all Series involved
have the same label or not whereas in case of ndarrays it raises an error.
NCERT - EXERCISE
2. What is a DataFrame and how is it different from a 2-D array?
3. How are DataFrames related to Series?
4. What do you understand by the size of (i) a Series, (ii) a DataFrame?
9. Create the following DataFrame Sales containing year wise sales figures
for five sales persons in INR.
Use the years as column labels, and sales person names as row labels.
10. Use the DataFrame created in Question 9 above to do the following:
a) Display the row labels of Sales.
b) Display the column labels of Sales.
c) Display the data types of each column of Sales.
d) Display the dimensions, shape, size and values of Sales.
e) Display the last two rows of Sales.
f) Display the first two columns of Sales.
g) Create a dictionary using the following data. Use this dictionary to create a DataFrame Sales2.
h) Check if Sales2 is empty or it contains data.
11. Use the DataFrame created in Question 9 above to do the following:
a) Append the DataFrame Sales2 to the DataFrame Sales.
b) Change the DataFrame Sales such that it becomes its transpose.
c) Display the sales made by all sales persons in the year 2017.
d) Display the sales made by Madhu and Ankit in the year 2017 and 2018.
e) Display the sales made by Shruti 2016.
f) Add data to Sales for salesman Sumeet where the sales made are [196.2, 37800, 52000, 78438,
38852] in the years [2014, 2015, 2016, 2017,2018] respectively.
g) Delete the data for the year 2014 from the DataFrame Sales.
XII – IP (2025.2026 Material & Old CBSE Questions) 110 2. DataFrames
h) Delete the data for sales man Kinshuk from the DataFrame Sales.
i) Change the name of the salesperson Ankit to Vivaan and Madhu to Shailesh.
j) Update the sale made by Shailesh in 2018 to 100000.
k) Write the values of DataFrame Sales to a comma separated file SalesFigures.csv on the disk. Do not write the row labels and
column labels.
l) Read the data in the file SalesFigures.csv into a DataFrame SalesRetrieved and Display it. Now update the row labels and
column labels of SalesRetrieved to be the same as that of Sales.
Activity
2.7 Use the type function to check the datatypes of ResultSheet and ResultDF. Are they the same?
Similar Answer)
>>> df
>>>type(df)
<class 'pandas.core.frame.DataFrame'>
>>>type(df.Eng)
<class 'pandas.core.series.Series'>
2.8 Accessing DataFrames Element through Slicing Concept
a) Using the DataFrame ResultDF, write the statement to access Marks of Arnab in Maths.
b) Create a DataFrame having 5 rows and write the statement to get the first 4 rows of it.
Think and Reflect:
Can you write a program to count the number of rows and columns in a DataFrame?
>>> array1 = np.array([10,20,30])
>>> array2 = np.array([100,200,300])
>>> array3 = np.array([-10,-20,-30, -40])
dFrame5 = pd.DataFrame([array1, array3, array2], columns=[ 'A', 'B', 'C', 'D'])
What would happen if we pass 3 columns or 5 columns instead of 4 in the above code? What is the reason?
Can you write a program to count the number of rows and columns in a DataFrame?
What if in the rename function we pass a value for a row label that does not exist? (Renaming Row Labels of a DataFrame
concept)
What would happen if the label or row index passed is not present in the DataFrame? (Accessing DataFrames Element through
Indexing)
How can you check whether a given DataFrame has any missing value or not?
Problem on Outputs Using loc,iloc,at
Given a data frame mdf as shown below:
X Y Z
0 10 20 30
1 40 50 60
Write program:
import pandas as pd
D={'X':{0:10,1:40},'Y':{0:20,1:50},'Z':{0:30,1:60}}
mdf=pd.DataFrame(D)
What will be the output produced by the following code?
print("I : ", mdf.iloc[0][0])
print("II : ", mdf.iloc[0]["Z"])
print("III : ", mdf.at[1,"X"])
print("IV : ",mdf.iat[1,2])
Outputs
I : 10
II : 30
III : 40
IV : 60
EXTRA CONCEPT IN NCERT
(A) Joining
We can use the pandas.DataFrame.append() method to merge two DataFrames. It appends rows of the second
DataFrame at the end of the first DataFrame. Columns not present in the first DataFrame are added as new columns.
For example, consider the two DataFrames—dFrame1 and dFrame2 described below.
XII – IP (2025.2026 Material & Old CBSE Questions) 111 2. DataFrames
Let us use the append() method to append dFrame2 to dFrame1:
>>> dFrame1=pd.DataFrame([[1, 2, 3], [4, 5],[6]],
columns=['C1', 'C2', 'C3'], index=['R1', 'R2', 'R3'])
>>> dFrame1 C1 C2 C3
R1 1 2.0 3.0
R2 4 5.0 NaN
R3 6 NaN NaN
>>> dFrame2=pd.DataFrame([[10, 20], [30], [40,50]],
columns=['C2', 'C5'], index=['R4', 'R2', 'R5'])
>>> dFrame2
C2 C5
R4 10 20.0
R2 30 NaN
R5 40 50.0
>>> dFrame1=dFrame1.append(dFrame2)
>>> dFrame1
C1 C2 C3 C5
R1 1.0 2.0 3.0 NaN
R2 4.0 5.0 NaN NaN
R3 6.0 NaN NaN NaN
R4 NaN 10.0 NaN 20.0
R2 NaN 30.0 NaN NaN
R5 NaN 40.0 NaN 50.0
Alternatively, if we append dFrame1 to dFrame2, the rows of dFrame2 precede the rows of dFrame1. To get the column labels
appear in sorted order we can set the parameter sort=True. The column labels shall appear in unsorted order when the parameter
sort = False.
# append dFrame1 to dFrame2
>>> dFrame2 =dFrame2.append(dFrame1,sort=’True’)
>>> dFrame2
C1 C2 C3 C5
R4 NaN 10.0 NaN 20.0
R2 NaN 30.0 NaN NaN
R5 NaN 40.0 NaN 50.0
R1 1.0 2.0 3.0 NaN
R2 4.0 5.0 NaN NaN
R3 6.0 NaN NaN NaN
# append dFrame1 to dFrame2 with sort=False
>>> dFrame2 = dFrame2.append(dFrame1, sort=’False’)
>>> dFrame2
C2 C5 C1 C3
R4 10.0 20.0 NaN NaN
R2 30.0 NaN NaN NaN
R5 40.0 50.0 NaN NaN
R1 2.0 NaN 1.0 3.0
R2 5.0 NaN 4.0 NaN
R3 NaN NaN 6.0 NaN
The parameter verify_integrity of append()method may be set to True when we want to raise an error if the row labels are duplicate.
By default, verify_integrity = False. That is why we could append the duplicate row with label R2 when appending the two
DataFrames, as shown above.
The parameter ignore_index of append()method may be set to True, when we do not want to use row index labels. By default,
ignore_index = False.
>>> dFrame1 = dFrame1.append(dFrame2, ignore_ index=True)
>>> dFrame1
C1 C2 C3 C5
0 1.0 2.0 3.0 NaN
1 4.0 5.0 NaN NaN
2 6.0 NaN NaN NaN
3 NaN 10.0 NaN 20.0
4 NaN 30.0 NaN NaN
5 NaN 40.0 NaN 50.0
The append()method can also be used to append a
series or a dictionary to a DataFrame.
Think and Reflect: How can you check whether a given DataFrame has any missing value or not?
XII – IP (2025.2026 Material & Old CBSE Questions) 112 2. DataFrames
IMPORTING/EXPORTING DATA BETWEEN CSV FILES & DATA FRAMES
3. IMPORTING & EXPORTING FILES FROM CSV FILES
Topics:
1. CSV Files & Its Creation
2. Importing CSV Files (CSV to DataFrames).
3. Exporting CSV Files (DataFrames to CSV).
1. CSV Files & Its Creation
Most data files that we use to store data such as spreadsheet files or database tables, also store the data
in 2D tabular formats. Since dataframes can also hold data in similar way, you can transfer data from
dataframe to such data files (or tables) or from files (or tables) into dataframes.
In this chapter, we will learn how to transfer data to/from a .CSV file from/into a dataframe.
A CommaSeparated Values (CSV) file is a text file where values are separated by comma. Each line
represents a record (row). Each row consists of one or more fields (columns). They can be easily handled
through a spreadsheet application.
Ex: Tabular Data - CSV File
Observe the following in CSV:
Each row of the table is stored in one row i.e., the number of rows in a CSV file are equal to number
of rows in the sheet.
The field values of a row are stored together with commas after every field value; but after the last
field’s value in a line/row, no comma is given, just the end of line.
CSV format advantages:
A simple, compact and ubiquitous format for data storage.
A common format for data interchange.
It can be opened in popular spreadsheet packages like MS-Excel,calc etc., also with notepad, etc.
Nearly all spreadsheets and databases support import/export to csv format.
How to Create a CSV File (This concept ie Creation is just to understand)
(A) Using Excel:
(i) Type the data in the tabular form
(ii) Goto (iii) Then in the next window select “Save as Type”
File→Save As→ Select Other formats as “CSV(Comma delimited)” and click on “Save”.
(B) Using Notepad:
(i)Type the data with comma separated values as follows:
XII – IP (2025.2026 Material & Old CBSE Questions) 113 3. CSV Files
(ii) Goto File🡪Save As
(iii) Select “Save as type” as “All Files” and enter “File name” as “yourfilename.csv”
Ex: mycsvfile.csv
Then click on “Save”.
2. IMPORTING CSV FILES (CSV to DataFrames).
Reading from a CSV file to DataFrame:
read_csv( ) of Pandas Library is used to read data from a CSV file in our dataframe.
Syntax:<DF>=pandas.read_csv(<filepath>, sep=’,’,header=0,)
• The first parameter to the read_csv() is the name of the comma separated data file along with its path.
• The parameter sep specifies whether the values are separated by comma, semicolon, tab, or any other character.
The default value for sepis a space.
• The parameter header specifies the number of the row whose values are to be used as the column names.
It also marks the start of the data to be fetched.
header=0 implies that column names are inferred from the first line of the file.
By default, header=0.
We can exclusively specify column names using the parameter names while creating the DataFrame using
the read_csv() function.
For example, in the following statement, names parameter is used to specify the labels for columns of the
DataFrame marks1:
>>> marks1= pd.read_csv("C:/NCERT/ResultData1.csv", sep=",", names= ['RNo','StudentName', 'Sub1', 'Sub2'])
Ex: df=pd.read_csv(“D:\\XII\\veg.csv”) # (or) df=pd.read_csv(“D:/XII/veg.csv”)
Note : If we use ‘\’, it should be mention as escape sequence ie ‘\\’.
(read from csv file in location D:\XII)
CSV file opend through notepad, through excel
Program to read a csv file “veg” from location “D:\XII”.
import pandas as pd
df=pd.read_csv("D:/XII/veg.csv")
print(df) # Here, it will take first row as column names.
Output:
Consider the following example: If the CSV file is without column names, it will take the first row as
column names.
XII – IP (2025.2026 Material & Old CBSE Questions) 114 3. CSV Files
import pandas as pd
df=pd.read_csv("D:/XII/studentsmarks.csv")
print(df)
Output
Note:for csv files that doesn’t have top row as column headers like above example, it will take the top row as
the column headers.
Reading CSV files and specifying own columns names:
To specify own column headings:
Syntax:<DF>=pd.read_csv(<filepath>, names=<”sequence containing column names”>)
Ex: df=pd.read_csv("D:/XII/studentsmarks.csv", names=[”RNo”,”Name”,”Marks”])
print(df)
Output:
header = None, can be used in the following conditions (both together):
(i) First row not to be used as header
(ii) Do not want to specify column headings.
(header = 0 means, first row of CSV will become as column headings,
header = None means, first row of CSV will become first row in Dataframe)
Syntax: <DF>=pandas.read_csv(<filepath>,header=None)
Then default column headings 0,1,2….will appear as column headers.
Ex Data:
df=pd.read_csv("D:/XII/studentsmarks.csv", header=None)
print(df)
Output
Consider the following situation:
The CSV file is having column heading, but you do not want to use them, you can use one of 2 following
alternative solutions.
(A) Argument names = <sequence of column
headings>, then the first row’s data will be taken as data.
Ex: df=pd.read_csv("D:/XII/veg.csv", names=["Number","VName",'Cost'])
XII – IP (2025.2026 Material & Old CBSE Questions) 115 3. CSV Files
(B) If we give argument header=None, then also it will take default headings as 0,1,2,…..
Ex: df=pd.read_csv("D:/XII/veg.csv",header=None)
skiprows<n>The number given with skip rows tells how many rows to be skipped from CSV while reading
data.
Syntax: <DF>=pandas.read_csv(<filepath>, names= <column names’ sequence>, skiprows=<n>)
(without skip rows)
Ex:
df=pd.read_csv("D:/XII/veg.csv", names=["Number","VName",'Cost'],skiprows=1)
print(df)
df=pd.read_csv("D:/XII/veg.csv",
names=["Number","VName",'Cost'],skiprows=3)
print(df)
pd.read_csv("D:/XII/veg.csv",names= ["Number","VName",'Cost'],skiprows=[0,2,3])
print(df)
(Without names argument and skip rows)
df=pd.read_csv("D:/XII/veg.csv")
print(df)
df=pd.read_csv("D:/XII/veg.csv",skiprows=3)
print(df)
XII – IP (2025.2026 Material & Old CBSE Questions) 116 3. CSV Files
df=pd.read_csv("D:/XII/veg.csv",skiprows=[0,3,4])
print(df)
df=pd.read_csv("D:/XII/veg.csv",header=None, skiprows=2)
print(df)
df=pd.read_csv("D:/XII/veg.csv", header=None,skiprows=[0,1,4])
print(df)
CSV File :Studentsmarks
df=pd.read_csv("D:/XII/studentsmarks.csv")
df=pd.read_csv("D:/XII/studentsmarks.csv", skiprows=3)
df=pd.read_csv("D:/XII/studentsmarks.csv", skiprows=[0,1,4])
print(df)
Get DataFrame Index Lables from CSV :
(One of Column header of a CSV file will become index labels of Importing DataFrame)
Ex:
df=pd.read_csv("D:/XII/veg.csv", index_col='Vegetable')
print(df)
To display costliest vegetable price:
df=pd.read_csv("D:/XII/veg.csv", index_col='Vegetable')
print(df)
print("Maximum Price Vegetable is ", df.Price.max( ))
XII – IP (2025.2026 Material & Old CBSE Questions) 117 3. CSV Files
Reading specified number of rows from CSV file:
nrows=<n>in read_csv( ), will read the specified number of rows from the CSV file.
CSV File : Veg
df=pd.read_csv("D:/XII/veg.csv",nrows=3)
print(df)
CSV File : Students Marks
df=pd.read_csv("D:/XII/studentsmarks.csv", nrows=3)
print(df)
tail( ) function :to display the bottom rows
Program to read first 3 records from “veg.csv” file and print the last two rows from the dataframe.
import pandas as pd
df=pd.read_csv("D:/XII/veg.csv",nrows=3)
print(df.tail(2))
Reading from CSV files having Separator Different from Comma:
Some CSV files are so created that their separator character is different from comma such as a
semicolon(;) or a pipe symbol(|), etc.
To read data from such CSV files, you need to specify an additional argument as sep=<separator
character>. If you skip this argument, then default separator character (comma) is considered.
For example, following command will read data from a CSV file where data has been separated using
semicolon :
Example:
df=pd.read_csv("D:/XII/Games.csv",sep=':')
print(df)
XII – IP (2025.2026 Material & Old CBSE Questions) 118 3. CSV Files
read_csv( ) full syntax
]
<DF>=pandas.read_csv(<filepath>, sep=<separator character>, names=<column names sequence>,
index_col=<column name>, header=None, skiprows=<n>, nrows=<n>
3. EXPORTING CSV FILES (DataFrames to CSV).
We can use the to_csv() function to save a DataFrame to a text or csv file.
Syntax:
<DF>.to_csv(<filepath>) (or) <DF>.to_csv(<filepath>,sep=<separator_character>)
Example Program to store DataFrame, which contains section wise toppers list of a class:
import pandas as pd
dict={'RNo':[15,7,5,12],'Name':['Srinidhi','Ratan','Maheswari','Suresh'],'Marks':[98.5,99.2,97.3,99.5]}
DF=pd.DataFrame(dict,index=['Sec A','SecB', 'SecC','Sec D'])
print(DF)
Output
To store this DF, we can write:
>>>DF.to_csv(“D:/XII/toppers.csv”)
The data from dataframe DF is stored in the csv file “toppers.csv” (in location D:\XII) with separator character
as comma.
When we open this file in any text editor or a spreadsheet, we will find the above data along with the row
labels and the column headers, separated by comma.
Note: (1) In case we do not want the column names to be saved to the file we may use the parameter
header=False.
(2) Another parameter index=False is used when we do not want the row labels to be written to the file on
disk.
For example:
>>> df.to_csv ( 'D:/XII/TestExp.csv', header=False, index= False)
As no separator has been mentioned, it will take default separator character, comma (,) to separate data in the
CSV file. Also, even if there exists a file with the same name at the given location, it will simply overwrite
the file without any warning.
Using a different separator (like ‘@’):
>>>df.to_csv( 'D:/XII/TestExp.csv', sep='@', header=False,index= False)
XII – IP (2025.2026 Material & Old CBSE Questions) 119 3. CSV Files
Using a different separator (like ‘|’):
Ex:DF.to_csv("D:/XII/toppers.csv",sep='|')
Handling NaN Values with to_csv( ):
If DataFrame has NaN values, Bydefault, the Missing/NaN values are stored as empty strings in CSV file.
If NaN Values exists in DataFrame, that will be displayed as empty in CSV Files
(empty comma (,) or empty ‘|’, etc will be displayed.)
Example Program
import pandas as pd
importnumpy as np
dict={'RNo':[15,7,5,12],'Name':['Srinidhi','Ratan', 'Maheswari',np.NaN],'Marks':[98.5,np.NaN,97.3,99.5]}
DF=pd.DataFrame(dict,
index=['Sec A','SecB','SecC','Sec D'])
DF.to_csv("D:/XII/toppers2.csv")
Then the following data will be stored in “toppers2.csv” file.
If separator is ‘|’
We can specify our own string that can be written for missing/NaN values by giving an argument
na_rep=<string>
Example: DF.to_csv("D:/XII/toppers2.csv", sep='|',na_rep="NULL")
to_csv( ) syntax:
<DF>.to_csv(<filepath>, sep=<separatorcharacter>,na_rep=<string>)
XII – IP (2025.2026 Material & Old CBSE Questions) 120 3. CSV Files
XII – IP – CBSE OLD QUESTIONS
CSV FILES
2.CBSE COMPARTMENT PAPER::2024.25
1. Ms. Shambhavi, a data analyst working on a college admission project, has created the following
DataFrame Sub_Details to store subjectwise details :
(b) Ms. Shambhavi has just created a folder named Project in the E: drive of her computer to store necessary
files related to the project. Write suitable Python statement to export the given DataFrame into the file
stud.csv, created inside project folder in E: drive.
A) Sub_Details.to_csv("E:\project\stud.csv") OR
Sub_Details.to_csv("E:/project/stud.csv") OR
Sub_Details.to_csv("E:\\project\\stud.csv") OR
Sub_Details.to_csv(r"E:\project\stud.csv")
3.CBSE SAMPLE PAPER::2024.25
1. Which of the following Python statements is used to import data from a CSV file into a Pandas
DataFrame
(Note: pd is an alias for pandas)?
(A) pd.open_csv('filename.csv') (B) pd.read_csv('filename.csv')
(C) pd.load_csv('filename.csv') (D) pd.import_csv('filename.csv')
A) (B) pd.read_csv('filename.csv')
4.CBSE BOARD PAPER::2023.24
7. Which of the following is NOT true with respect to CSV files ?
(i) Values are separated by commas.
(ii) to_csv( ) can be used to save a dataframe to a CSV file.
(iii) CSV file is created using a word processor.
(iv) CSV file is a type of text file.
A) All the options are true with respect to CSV files.
2.CBSE SAMPLE PAPER::2023.24
7. CSV stands for:
i. Column Separated Value ii. Class Separated Value iii. Comma Separated Value iv. None of the above
a) iii. Comma Separated Value
32. Ekam, a Data Analyst with a multinational brand has designed the DataFrame df that contains the four
quarter’s sales data of different stores as shown below:
Answer the following questions:
iii. OR
Write Python statement to export the DataFrame to a CSV file named data.csv stored at D: drive.
a) df.to_csv(“D:/data.csv”)
XII – IP (2025.2026 Material & Old CBSE Questions) 121 3. CSV Files
7. CBSE QUESTION PAPER::2021.22
4. The data of any CSV file can be shown in
which of the following software?
a) MS Word b) Notepad c) Spreadsheet d) All of the above
a) d
34. Nowadays for developing Machine learning projects programmers rely on CSV files rather than databases.
Why?
a) csv can be used with proprietary softwares only.
b) csv files can be downloaded from open source websites free of cost
c) csv files need not be imported while creating the projects
d) csv is a simple and well formatted mode for data storage
a) d
8. CBSE SAMPLE PAPER :: 2021.22
24. Which function will be used to read data from a CSV file into pandas data frame?
a. readcsv() b. to_csv() c. read_csv() d. csv_read()
a) c. read_csv()
NCERT TEXT GIVEN WORK
Create the MelaSale.csv using Python Pandas containing data as shown in table.
Day-wise mela sales data
XII – IP (2025.2026 Material & Old CBSE Questions) 122 3. CSV Files
DATA VISUALIZATION & CUSTOMISING PLOTS
The results obtained after analysis is used to make inferences or draw conclusions about data as well as to make
important business decisions.
Sometimes, it is not easy to infer by merely looking at the results. In such cases, visualisation helps in better
understanding of results of the analysis.
Data visualisation means graphical or pictorial representation of the data using graph, chart, etc. The purpose of
plotting data is to visualise variation or show relationships between variables.
Visualisation also helps to effectively communicate information to intended users.
Traffic symbols, ultrasound reports, Atlas book of maps, speedometer of a vehicle, tuners of instruments are few
examples of visualisation that we come across in our daily lives.
Visualisation of data is effectively used in fields like health, finance, science, mathematics, engineering, etc.
PyPlot is a collection of methods within matplotlib library, which allows user to construct 2D plots easily and
interactively.
Plotting using Matplotlib:
Matplotlib library is used for creating static, animated, and interactive 2D- plots or figures in Python.
It can be installed using the following pip command from the command prompt:
pip install matplotlib
For plotting using Matplotlib, we need to import its Pyplot module using the following command:
import matplotlib.pyplot as plt
Import PyPlot: (Use one of the following)
import matplotlib.pyplot
import matplotlib.pyplot as plt (or any valid identifier in place of pl)
from matplotlib import pyplot
Figure 4.1: Components of a plot
The pyplot module of matplotlib contains a collection of functions that can be used to work on a plot.
The plot() function of the pyplot module is used to create a figure. A figure is the overall window where the
outputs of pyplot functions are plotted.
A figure contains a plotting area, legend, axis labels, ticks, title, etc.
Each function makes some change to a figure: example, creates a figure, creates a plotting area in a figure,
plots some lines in a plotting area, decorates the plot with labels, etc. It is always expected that the data presented
through charts easily understood.
Hence, while presenting data we should always give a chart title, label the axis of the chart and provide legend
in case we have more than one plotted data.
To plot x versus y, we can write plt.plot(x,y). The show() function is used to display the figure created using
the plot() function.
List of Pyplot functions to plot different chart:
plot(\*args[, scalex, scaley, data]) Plot x versus y as lines and/or markers.
bar(x, height[, width, bottom, align, data]) Make a bar plot.
hist(x[, bins, range, density, weights, ...]) Plot a histogram.
XII – IP (2025.2026 Material & Old CBSE Questions) 123 4.Data Visualisation
Customisation of Plots
Pyplot library gives us numerous functions, which can be used to customise charts such as adding titles or legends.
grid([b, which, axis]) Configure the grid lines.
legend(\*args, \*\*kwargs Place a legend on the axes.
savefig(\*args, \*\*kwargs) Save the current figure
show(\*args, \*\*kw) Display all figures
title(label[,fontdict,loc,pad]) Set a title for the axes.
xlabel(xlabel[,fontdict, labelpad]) Set the label for the x-axis.
xticks([ticks, labels]) Get or set the current tick locations and labels of the x-axis.
ylabel(ylabel[,fontdict, labelpad]) Set the label for the y-axis.
yticks([ticks, labels]) Get or set the current tick locations and labels of the y-axis
List of Pyplot functions to customise plots
Demo Program:
Program to display 4 CT marks of a student using line chart.
import matplotlib.pyplot as plt
ctno=['CT1','CT2','CT3','CT4']
marks=[15,30,22,35]
plt.plot(ctno,marks)
plt.show()
Marker: (Changing marker type, size and colour)
It is also possible to specify each point in the line through a marker.
A marker is any symbol that represents a data value in a line chart or a scatter plot. (The data points being plotted on
a graph/chart are called markers.)
We can give following additional optional arguments in plot() function:
marker=<valid marker type>,markersize=<in points>, markeredgecolor=<valid color>
We can specify marker type as dots, crosses, diamonds, etc. If you do not specify marker type, data points will not be
marked specifically on the line chart and its default type will be the same as that of the line type.
Marker Symbol Description Marker Symbol Description
‘.’ Point marker “8” octagon
‘,’ Pixel marker “s” square
‘o’ Circle marker “p” Pentagon
“v” triangle_down “P” plus (filled)
“^” triangle_up “*” Star
“<” triangle_left “h” hexagon1
“>” triangle_right “H” hexagon2
“1” tri_down “+” Plus
“2” tri_up “x” X
“3” tri_left “X” x (filled)
“4” tri_right “D” Diamond
Some of the Matplotlib Markers
Colour : It is also possible to format the plot further by changing the colour of the plotted data.
We can either use character codes or the color names as values to the parameter color in the plot( ).
XII – IP (2025.2026 Material & Old CBSE Questions) 124 4.Data Visualisation
Colour abbreviations for plotting
Important Point: Continuous data are measured while discrete data are obtained by counting.
Height, weight are examples of continuous data. It can be in decimals. Total number of students
in a class is discrete. It can never be in decimals.
The Pandas Plot function (Pandas Visualisation):
In previous Programs, we learnt that the plot( ) function of the pyplot module of matplotlib can
be used to plot a chart.
However, starting from version 0.17.0, Pandas objects Series and DataFrame come
equipped with their own .plot() methods.
This plot() method is just a simple wrapper around the plot() function of pyplot.
Thus, if we have a Series or DataFrame type object (let's say 's' or 'df') we can call the plot method by writing:
s.plot() or df.plot()
The plot( ) method of Pandas accepts a considerable number of arguments that can be used to plot a variety of graphs.
It allows customising different plot types by supplying the kind keyword arguments. The general syntax is:
plt.plot(kind),where kind accepts a string indicating the type of .plot, as listed in the following table.
In addition, we can use the matplotlib.pyplot methods and functions also along with the plt() method of Pandas
objects.
kind = Plot type
line Line plot (default)
bar Vertical bar plot
barh Horizontal bar plot
hist Histogram
Others (Following are not in syllabus)
box Boxplot
area Area plot
pie Pie plot
scatter Scatter plot
Arguments accepted by kind for different plots
we will learn to use plot() function to create various types of charts with respect to the type of data stored in DataFrames.
Ex: ctno=['CT1','CT2','CT3','CT4']
marks=[15,30,22,35]
pl.plot(ctno,marks,'b',linewidth=10,marker='s',
markersize=20,markeredgecolor='r')
Note :(1) We can combine the marker type with color code
e.g.,’r+’ when given for line color marks the color as ‘red’ and markertype as plus(‘+’), ‘b3’ means line color marks the color as
‘blue’ and markertype as ‘tri left marker’.
(2) When you do not specify markeredgecolor separately in plot(), the marker takes the same color as the line.
(3) If you do not specify the linestyle separately along with linecolor-markerstyle combination (eg.,’r+’), python will only plot the
markers and not the line. To get the line, specify linestyle argument also. Ex: pl.plot(ctno,marks,’rd’).
title: To add a title to your plot, we need to call function title( )
Syntax:<matplotlib.pyplot>.title(<title string>)
Ex: pl.title(“Vegetable Rates at various places”)
pl.plot(x-axis values sequence, y-axis values sequence)
pl.xlabel(“Label here”) #To display x-axis label
pl.ylabel(“Label here”) #To display y-axis label
pl.show( ) # To display the chart/plot.
Setting limits for X-axis and Y-axis:
PyPlot by default, tries to find best fitting range for X-axis and Y-axis depending on the data being plotted.
XII – IP (2025.2026 Material & Old CBSE Questions) 125 4.Data Visualisation
We can give xlimits and ylimits as follows:
<matplotlib.pyplot>.xlim(<xmin>,<xmax>)
<matplotlib.pyplot>.ylim(<ymin>,<ymax>)
Setting ticks for Axes:
By default, PyPlot will automatically decide which data points will have ticks on the axes, but we can also
decide which data points will have tick marks on X and Y-axes.
Syntax (for X-axis): xticks(<sequence containing tick data points>,[<optional sequence containing tick labels>])
Syntax (for Y-axis): yticks(<sequence containing tick data points>,[<optional sequence containing tick labels>])
Adding Lagends:
A legend is a color or mark linked to a specific data range plotted. When we plot multiple ranges on a single
plot, it becomes necessary that legends are specified.
To add a legend, <matplotlib.pyplot>.legend(loc=<position number or string>)
Concerned label should be given in plot( ) statement.
Position Numbers – 1.upper right, 2.upper left, 3.lower left, 4.lower right. (Default : 2 ie upper left)
Saving a Figure:
savefig( ) function is used to save a plot created using pyplot functions for later use or for keeping records.
Syntax:<matplotlib.pyplot>.savefig(<string with filename and path>)
We can save figures formats like .pdf, .png, .eps, etc
Ex: pl.savefig(“myfile.pdf”) #stores the plot in current directory
pl.savefig(“D:\\data\\myfile.pdf”) # it store the pdf file in D Drive, data folder
LINE CHARTS
A line plot is a graph that shows the frequency of data along a number line. It is used to show
continuous dataset.
A line plot is used to visualise growth or decline in data over a time interval.
(A line chart or line graph is a type of chart which displays information as a series of data points called ‘markers’ connected
by straight line segments. With PyPlot, a line chart is created using plot( ) function. )
Program to display 4 CT marks of a student using line chart.
importmatplotlib.pyplot as pl
ctno=['CT1','CT2','CT3','CT4']
marks=[29,32,34,35]
pl.xlabel("CT Number")
pl.ylabel("CT Marks")
pl.plot(ctno,marks)
pl.show()
Specifying plot size:We can change the plot size as per our requirements.
Syntax:
<matplotlib.pyplot>.figure(figsize=(<width>,<length>))
Ex: matplotlib.pyplot.figure(figsize=(15,8)) (or pl.figure(figsize=(15,8))
Here 15 units wide ie., x coordinates, 8 units long ie.,y coordinates.
To show grid: pl.grid(True)
Program to display 4 CT marks of a student using line chart. (With desired plotsize and grid)
importmatplotlib.pyplot as pl
ctno=['CT1','CT2','CT3','CT4']
marks=[29,32,34,35]
pl.figure(figsize=(16,8))
pl.xlabel("CT Number")
pl.ylabel("CT Marks")
pl.plot(ctno,marks)
pl.grid(True)
pl.show()
Applying various settings in plot() function:
Changing Line Colour:
Syntax: <matplotlib.pyplot>.plot(<data1>,[,data2],<colour code>)
Ex: pl.plot(ctno,marks,’r’)
Character Colour Character Colour
‘b’ blue ‘m’ Magenta
‘g’ green ‘y’ Yellow
‘r’ red ‘k’ Black
‘c’ cyan ‘w’ White
XII – IP (2025.2026 Material & Old CBSE Questions) 126 4.Data Visualisation
Note: 1. If we skip colour information, python will plot multiple lines in the same plot with different colours.
2. We can also write full colour names like ‘red’,’light green’ or by using hex strings like ‘#008000’, etc.
Linewidth and Line Style :
The linewidth and linestyle property can be used to change the width and the style of the line chart.
Linewidth is specified in pixels. The default line width is 1 pixel showing a thin line. Thus, a number greater than 1 will
output a thicker line depending on the value provided.
Changing Line Width:
Ex: plt.plot(ctno,marks,linewidth=2)
Changing Line Style:
linestyle (or) ls = [‘solid’,’dashed’,’dashdot’,’dotted’]
Ex:pl.plot(ctno,marks,linewidth=3,linestyle=’dashed’)
linestyle (ls): We can also set the line style of a line chart using the linestyle parameter. It can take a string such as
"solid", "dotted", "dashed" or "dashdot".
Program to display 4 CT marks of a student using line chart. (With different line width and life style)
importmatplotlib.pyplot as pl
ctno=['CT1','CT2','CT3','CT4']
marks=[29,32,34,35]
pl.figure(figsize=(16,8))
pl.plot(ctno,marks,'r',linewidth=10,linestyle='dashed')
pl.xlabel("CT Number")
pl.ylabel("CT Marks")
pl.plot(ctno,marks)
pl.grid(True)
pl.show()
ls=’solid’ ls=’dashed’ linestyle=’dashdot’ linestyle=’dotted’
Note :“We can use either linestyle or ls. Default linestyle is “solid”.
Ex (If we swapped the limits (min,max) as (max,min), then the plot gets flipped):
import matplotlib.pyplot as pp
X=[0,1,2,3]
Y=[5.0,25.0,45.0,20.0]
pp.xlim(-2,4)
pp.plot(X,Y)
pp.show()
import matplotlib.pyplot as pp
X=[0,1,2,3]
Y=[5.0,25.0,45.0,20.0]
pp.xlim(4,-2)
pp.plot(X,Y)
pp.show()
Demo Program (xticks and yticks):
import matplotlib.pyplot as pp
X=[0,1,2,3]
Y=[5.0,25.0,45.0,20.0]
pp.xticks([0.5,1,5])
pp.yticks([10,15,40])
pp.plot(X,Y)
pp.show()
NCERT TEXT BOOK - EXAMPLES
Let us consider that in a city, the maximum temperature of a day is recorded for three consecutive days.
Program 4-1 demonstrates how to plot temperature values for the given dates. The output generated is a line chart.
Program 4-1 Plotting Temperature against Height
XII – IP (2025.2026 Material & Old CBSE Questions) 127 4.Data Visualisation
import matplotlib.pyplot as plt
#list storing date in string format
date=["25/12","26/12","27/12"]
#list storing temperature values
temp=[8.5,10.5,6.8]
#create a figure plotting temp versus date
plt.plot(date, temp)
#show the figure
plt.show() Figure 1.
In program 4-1, plot() is provided with two parameters, which indicates values for x-axis and y-axis, respectively.
The x and y ticks are displayed accordingly. As shown in Figure 4.2, the plot() function by default plots a
line chart. We can click on the save button on the output window and save the plot as an image. A figure can also
be saved by using savefig() function. The name of the figure is passed to the function as parameter.
For example: plt.savefig('x.png').
In the previous example, we used plot() function to plot a line graph. There are different types of data available for
analysis. The plotting methods allow for a handful of plot types other than the default line plot, as listed in Table 4.1.
(from our syllabus) Choice of plot is determined by the type of data we have.
Program 4-2 Plotting a line chart of date versus temperature by adding Label on X and Y axis, and adding a
Title and Grids to the chart.
import matplotlib.pyplot as plt
date=["25/12","26/12","27/12"]
temp=[8.5,10.5,6.8]
plt.plot(date, temp)
plt.xlabel("Date") #add the Label on x-axis
plt.ylabel("Temperature") #add the Label on y-axis
plt.title("Date wise Temperature") #add the title to the chart
plt.grid(True) #add gridlines to the background
plt.yticks(temp)
plt.show() Figure 2
In the above example, we have used the xlabel, ylabel, title and yticks functions. We can see that compared to Figure
1, the Figure 2 conveys more meaning, easily. We will learn about customisation of other plots in later sections.
Let us write the Program 4-3 applying some of the customisations.
Program 4-3 Consider the average heights and weights of persons aged 8 to 16 stored in the following two lists:
height = [121.9,124.5,129.5,134.6,139.7,147.3,152.4, 157.5,162.6]
weight= [19.7,21.3,23.5,25.9,28.5,32.1,35.7,39.6, 43.2]
Let us plot a line chart where:
i. x axis will represent weight
ii. y axis will represent height
iii. x axis label should be “Weight in kg”
iv. y axis label should be “Height in cm”
v. colour of the line should be green
vi. use * as marker
vii. Marker size as10
viii. The title of the chart should be “Average weight with respect to average height”.
ix. Line style should be dashed
x. Linewidth should be 2.
***
import matplotlib.pyplot as plt
import pandas as pd
height=[121.9,124.5,129.5,134.6,139.7,147.3,152.4, 157.5,162.6]
weight=[19.7,21.3,23.5,25.9,28.5,32.1,35.7,39.6,43.2]
df=pd.DataFrame({"height":height,"weight":weight})
plt.xlabel('Weight in kg') #Set xlabel for the plot
plt.ylabel('Height in cm') #Set ylabel for the plot
plt.title('Average weight with respect to average height') #Set chart title:
#plot using marker'-*' and line colour as green
plt.plot(df.weight,df.height,marker='*',markersize=10, color='green',linewidth=2, linestyle='dashdot')
plt.show()
XII – IP (2025.2026 Material & Old CBSE Questions) 128 4.Data Visualisation
***
In the above we created the DataFrame using 2 lists, and in the plot function we have passed the height and weight
columns of the DataFrame.
The output is shown in following figure.
Line chart showing average weight against average height
Program 4-4 Smile NGO has participated in a three week cultural mela. Using Pandas,
they have stored the sales (in Rs) made day wise for every week in a CSV file named
“MelaSales.csv”, as shown in Table 4.6.
Table 4.6 Day-wise mela sales data
Depict the sales for the three weeks using a Line chart. It should have the
following:
i. Chart title as “Mela Sales Report”.
ii. axis label as Days.
iii. axis label as “Sales in Rs”.
Line colours are red for week 1, blue for week 2 and brown for week 3.
***
import pandas as pd
import matplotlib.pyplot as plt
# reads "MelaSales.csv" to df by giving path to the file
df=pd.read_csv("MelaSales.csv")
#create a line plot of different color for each week
df.plot(kind='line', color=['red','blue','brown'])
# Set title to "Mela Sales Report"
plt.title('Mela Sales Report')
# Label x axis as "Days"
plt.xlabel('Days')
# Label y axis as "Sales in Rs"
plt.ylabel('Sales in Rs')
#Display the figure
plt.show()
***
The Figure 4.5 displays a line plot as output for Program 4-4. Note that the legend is displayed by default associating
the colours with the plotted data.
The line plot takes a numeric value to display on the x axis and hence uses the index (row labels) of the DataFrame in
the above example. Thus, x tick values are the index of the DataFramedf that contains data stored in MelaSales.CSV.
Customising Line Plot :
We can substitute the ticks at x axis with a list of values
of our choice by using plt.xticks(ticks,label) where ticks is a list of locations(locs) on x axis at which ticks should be
placed, label is a list of items to place at the given ticks.
Program 4-5 Assuming the same CSV file, i.e., MelaSales.CSV, plot the line chart with following customisations:
Maker ="*" Marker size=10
linestyle="--" Linewidth =3
Program:
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv("D:/MelaSales.csv")
XII – IP (2025.2026 Material & Old CBSE Questions) 129 4.Data Visualisation
#creates plot of different color for each week
df.plot(kind='line', color=['red','blue','brown'],
marker="*",markersize=10,linewidth=3,linestyle="--")
plt.title('Mela Sales Report')
plt.xlabel('Days')
plt.ylabel('Sales in Rs')
#store converted index of DataFrame to a list
ticks = df.index.tolist()
#displays corresponding day on x axis
Day=["Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday","Sunday"]
plt.xticks(ticks,Day)
plt.show()
Above picture is generated as output of Program 4-5 with xticks as Day names.
The line plot in Figure 4.6 shows that the sales for all the weeks increased during the weekend. Other than weekends,
it also shows that the sales increased on Wednesday for Week 1, on Thursday for Week 2 and on Tuesday for Week 3.
BAR CHARTS
A bar graph or a bar chart is a graphical display of data using bars of different heights. A bar chart can be
drawn vertically or horizontally using rectangles or bars of different heights/widths.
Each y value is plotted as bar on corresponding x-value on x-axis.
If you want that multiple commands affect a common bar chart, then either store all the related statements in a
Python script (.py file) with last statement being
<matplotlib.pyplot>.show()
Rakesh went to Raithu Bazar to purchase to buy vegetables.
Write a program to display him vegetable names and its rates
per KG using a bar chart.
importmatplotlib.pyplot as pp
vegetables=['Brinjal','Tamota','Onion','Beetroot',’Chilly’]
rates=[60,45,28,52,80]
pp.xlabel("Vegetable Names")
pp.ylabel("Vegetable Rates Per KG")
pp.bar(vegetables,rates)
pp.show()
Bharat compared rates of vegetables in Raithu Bazar and in Sunday
market. He found lot of variation in rates of vegetables per KG. Write
a program for the comparison using Bar chart.
importmatplotlib.pyplot as pp
vegetables=['Brinjal','Tamota','Onion','Beetroot']
rbazarrates=[60,45,28,52]
smarketrates=[95,70,45,35]
pp.xlabel("Vegetable Names")
pp.ylabel("RaithuBazar,Sunday Market Rates Per KG")
pp.bar(vegetables,smarketrates)
pp.bar(vegetables,rbazarrates)
pp.show()
Observe the following:
pp.bar(vegetables,rbazarrates)
pp.bar(vegetables,smarketrates)
Changing widths of the Bars in a Bar Chart:
Default width = 0.8 units
To specify common width (using a scalar value):
<matplotlib.pyplot>.bar(<x-sequence>,
<y-sequence>,width=<float value>)
Ex:pp.bar(vegetables,rates,width=0.4)
XII – IP (2025.2026 Material & Old CBSE Questions) 130 4.Data Visualisation
If you specify a scalar value (a single value) for width argument, then that width is applied to all the bars of the bar chart.
To specify different widths for different bars:
<matplotlib.pyplot>.bar(<x-sequence>,
<y-sequence>,width=<width values sequence>)
Ex:pp.bar(vegetables,rates,width=[0.4,0.2,0.5,0.8,0.4])
Note: The width values’ sequence in a bar( ) must have widths for all the bars,
i.e., its length must match the length of data sequences being plotted, otherwise
Python will report an error.
Changing the colors of the Bars:
By default, a bar chart draws bars with same default color.
To specify common color:
<matplotlib.pyplot>.bar(<x-sequence>,
<y-sequence>,color=<color code/name>)
When we specify single color name or single color code with color argument of
the bar( ) function, the specified color is applied to all the bars of the bar chart
i.e., all bars of the bar chart have the same common color.
To specify different colors for different Bars:
<matplotlib.pyplot>.bar(<x-sequence>,
<y-sequence>,color=<color codes squence/color names>)
Ex:pp.bar(vegetables,rates,width=[0.4,0.2,0.5,0.8,0.4], color=['b','red','k','g','y'])
Creating Multiple Bar Charts:
CTMarks is a list having 5 subject marks for CT1 & CT2. Create a bar chart that
plots these two sub lists of CTMarks in a single chart. Keep the width of each bar
as 0.3
importmatplotlib.pyplot as pl
importnumpy as np
CTMarks=[[32,37,39,29,25],[33,38,37,30,28]]
X=np.arange(5) #it gives 0,1,2,3,4
pl.bar(X+0.00,CTMarks[0],color='b',width=0.30)
pl.bar(X+0.30,CTMarks[1],color='g',width=0.30)
pl.show()
Creating a Horizontal Bar Chart:
Use barh( ) instead of bar( ).
The label that you give to x-axis in bar( ), will become y-axis label in
barh( )
Ex:
importmatplotlib.pyplot as pp
vegetables=['Brinjal','Tamota','Onion','Beetroot','Chilly']
rates=[60,45,28,52,80]
pp.xlabel("Vegetable Rates Per KG")
pp.ylabel("Vegetable Names")
pp.barh(vegetables,rates)
pp.show()
Rakesh went to Raithu Bazar to purchase to buy
vegetables. Program to program to display him vegetable
names and its rates per KG using a bar chart. Show title also.
import matplotlib.pyplot as pp
vegetables=['Brinjal','Tamota','Onion', 'Beetroot','Chilly']
rates=[60,45,28,52,80]
pp.xlabel("Vegetable Names")
pp.ylabel("Vegetable Rates Per KG")
pp.title("Vegetable Rates at various places")
pp.bar(vegetables,rates)
pp.show()
Demo Program (Using NP array):
import matplotlib.pyplot as pp
import numpy as np
X=np.arange(4) #[0,1,2,3]
Y=[5.0,25.0,45.0,20.0]
pp.bar(X,Y)
pp.title("A sample Bar Chart")
pp.show()
XII – IP (2025.2026 Material & Old CBSE Questions) 131 4.Data Visualisation
Demo Program (xlimits & ylimits):
import matplotlib.pyplot as pp
import numpy as np
X=np.arange(4) #[0,1,2,3]
Y=[5.0,25.0,45.0,20.0]
pp.xlim(-3.0,3.5)
pp.ylim(4,70)
pp.bar(X,Y)
pp.title("A sample Bar Chart")
pp.show()
Note: 1. While setting up the limits for axes, we must keep in
mind that only the data that falls into the limits of X and Y-axes
will be plotted, rest of the data will not show in the plot.
2. If we swapped the limits (min,max) as (max,min), then the plot
gets flipped.
Demo Program (xticks and yticks):
import matplotlib.pyplot as pp
X=[0,1,2,3]
Y=[5.0,25.0,45.0,20.0]
pp.xticks([0.5,1,5])
pp.yticks([10,15,40])
pp.bar(X,Y)
pp.show()
Program : “ABC” school celebrated volunteering week where each section of class VI dedicated a day for collecting
amount for charity being supported by the school. Section A volunteered on Monday, B on Tuesday, etc There are six
sections in class VI. Amounts collected by section A to F are 5000,4500,6000,3200,5500,6200. Write a program to
plot the collected amount vs. days using a bar chart. The ticks on X-axis should have Day names. The graph should
have proper title and axes titles.
***
import matplotlib.pyplot as pp
import numpy as np
amount=[5000,4500,6000,3200,5500,6200]
X=np.arange(6) #0,1,2,3,4,5
pp.title("Donations - Week Collection")
pp.bar(X,amount,color='blue',width=0.3)
pp.xticks(X,['Mon','Tue','Wed','Thu','Fri','Sat'])
pp.xlabel("Days")
pp.ylabel("Donation Amount Collected")
pp.show()
Legends Demo Program:
5 subject marks for 3 CT Exams of a student.
import matplotlib.pyplot as pl
import numpy as np
CTMarks=[[32,37,39,29,25],[33,38,37,30,28],
[34,33,39,40,35]]
X=np.arange(5) #it gives 0,1,2,3,4
pl.bar(X+0.00,CTMarks[0],color='b',width=0.20,
label='CT 1 Marks')
pl.bar(X+0.20,CTMarks[1],color='g',width=0.20,
label='CT 2 Marks')
pl.bar(X+0.40,CTMarks[2],color='k',width=0.20,
label='CT 3 Marks')
pl.legend(loc='upper right') #or 1 instread of upper right
pl.title("3 CT Marks of a student")
pl.xlabel("Subjects")
pl.ylabel("CTs")
pl.show()
XII – IP (2025.2026 Material & Old CBSE Questions) 132 4.Data Visualisation
FROM NCERT TEXT BOOK
To plot a bar chart, we will specify kind=’bar’.
We can also specify the DataFrame columns to be used as x
and y axes.
Let us now add a column “Days” consisting of day names to
“MelaSales.csv”.
Ex:
Day-wise sales data along with Day’s names
Note: If we do not specify the column name for the x
parameter in the plot(), the bar plot will plot all the columns of the DataFrame with the index (row label) of
DataFrame at x axis which is a numeric starting from 0.
Program 4-6 This program displays the Python script to display Bar plot for the “MelaSales.csv” file with column Day
on x axis as shown below in Figure 4.7
***
import pandas as pd
df= pd.read_csv('D:/MelaSales.csv')
import matplotlib.pyplot as plt
# plots a bar chart with the column "Days" as x axis
df.plot(kind='bar',x='Day',title='Mela Sales Report')
#set title and set ylabel
plt.ylabel('Sales in Rs')
plt.show()
Customising Bar Chart:
We can also customise the bar chart by adding certain
parameters to the plot function. We can control the edgecolor of the bar, linestyle and linewidth. We can also control
the color of the lines. The following example shows various customisations on the bar chart of Figure 4.8
Program 4-7 Let us write a Python script to display Bar plot for the “MelaSales.csv” file with column Day on x axis,
and having the following customisation:
● Changing the color of each bar to red, yellow and
purple.
● Edgecolor to green
● Linewidth as 2
● Line style as "--"
***
import pandas as pd
import matplotlib.pyplot as plt
df= pd.read_csv('D:/MelaSales.csv')
# plots a bar chart with the column "Days" as x axis
df.plot(kind='bar',x='Day',title='Mela Sales
Report',color=['red','yellow','purple'],
edgecolor='Green',linewidth=2,linestyle='--')
#set title and set ylabel
plt.ylabel('Sales in Rs')
plt.show()
A bar chart as output of Program 4-7
Think and Reflect: How can we make the bar chart of above Figure horizontal?
HISTOGRAMS
A histogram is a summarization tool for discrete or continuous data.
A histogram provides a visual interpretation of numerical data by showing the number of data points that fall
within a specified range of values (called bins).
It is similar to a vertical bar graph. Histogram, unlike a vertical bar graph, shows no gaps between the bars.
Visual representation of data distribution Can display large set of data
Histograms are column-charts, where each column represents a range of values, and the height of a
column corresponds to how many values are in that range.
To make a histogram, the data is sorted into "bins" and the number of data points in each bin is counted.
The height of each column in the histogram is then proportional to the number of data points its bin contains.
The df.plot(kind=’hist’) function automatically selects the size of the bins based on the spread of
values in the data.
XII – IP (2025.2026 Material & Old CBSE Questions) 133 4.Data Visualisation
Point: If we do not specify Bins are the number of intervals you want to divide all of your data into,
such that it can be displayed as bars on a histogram.
hist( ) function
Note:
If we do not specify Bins are the number of intervals
you want to divide all of your data into, such that it can be displayed as bars on a histogram.
Write a program to plot ages of 20 citizens using histogram
:
import matplotlib.pyplot as pl
x=[23,45,21,13,34,45,56,67,87,57,83,89,45,56,67,4,1,56,67,45]
pl.hist(x)
pl.xlabel("ages")
pl.ylabel("count")
pl.show()
pl.hist(x,ec='red') #ec means edge color
pl.hist(x,bins=5,ec='red')
Taking bins as a sequence :
pl.hist(x,bins=[1,13,20,40,60,100],ec='red')
Intervals :
[1,13) - 1,2,….12
[13,20) – 13,14,….19
[20,40) – 20,21…..39
[40,60) – 40,41,…..59
[60,100] – 60,61,…100
pl.hist(x,"auto",ec='red')
Auto – it will take number of bins by its own
pl.hist(x,20,ec='red')
XII – IP (2025.2026 Material & Old CBSE Questions) 134 4.Data Visualisation
pl.hist(x,"auto",(1,200),ec='red')
Range : minimum and maximum value of x as range
cumulative = True
In every interval, Present interval value + Smaller Values
cumulative = -1
In every interval, Present interval value + Bigger Values
histtype( ) :Type of histogram to draw
pl.hist(x,ec='red',histtype='step')
bar– default
barstacked – if multiple set of datas one above
another, stacked bar.
Step – line plot ie unfilled
Stepfilled – line plot ie filled
histtype=‘bar' histtype=‘barstacked' histtype='step' histtype='stepfilled’
align
align : Horizontal alignment of the histogram bars. They are : mid, left, right, mid
mid – bin between the edges
pl.hist(x,ec='red',histtype='bar',align='mid')
XII – IP (2025.2026 Material & Old CBSE Questions) 135 4.Data Visualisation
align=‘left’ align=‘right’
Orientation
❖ horizontal (or) vertical.
❖ Default value is “vertical”
pl.hist(x,ec='red',orientation='horizontal')
NCERT TEXT – EXAMPLES
Program 4-8
import pandas as pd
import matplotlib.pyplot as plt
data = {'Name':['Arnav', 'Sheela', 'Azhar', 'Bincy', 'Yash','Nazar'],'Height' : [60,61,63,65,61,60],
'Weight' : [47,89,52,58,50,47]}
df=pd.DataFrame(data)
df.plot(kind='hist')
plt.show()
Figure 4.9: A histogram as output of Program 4-8
It is also possible to set value for the bins parameter,
for example,
df.plot(kind=’hist’,bins=20)
df.plot(kind='hist',bins=[18,19,20,21,22])
df.plot(kind='hist',bins=range(18,25))
Customising Histogram:
Taking the same data as above, now let see how the histogram can be customised.
Let us change the edgecolor, which is the border of each hist, to green. Also, let us change the line style to ":" and line
width to 2. Let us try another property called fill, which takes boolean values.
The default True means each hist will be filled with color and False means each hist will be empty.
Another property called hatch can be used to fill to each hist with pattern ( '-', '+', 'x', '\\', '*', 'o', 'O', '.').
In the Program 4-10, we have used the hatch value as "o".
Program 4-9
import pandas as pd
import matplotlib.pyplot as plt
data = {'Name':['Arnav', 'Sheela', 'Azhar','Bincy','Yash','Nazar'],'Height' : [60,61,63,65,61,60],
'Weight' : [47,89,52,58,50,47]}
df=pd.DataFrame(data)
df.plot(kind='hist',edgecolor='Green',linewidth=2,linestyle=':',fill=False,hatch='o')
XII – IP (2025.2026 Material & Old CBSE Questions) 136 4.Data Visualisation
plt.show()
Figure 4.10: Customised histogram as output of Program 4-9
Using Open Data :
There are many websites that provide data freely for anyone to download and do analysis, primarily for educational
purposes. These are called Open Data as the data source is open to the public. Availability of data for access and use
promotes further analysis and innovation. A lot of emphasis is being given to open data to ensure transparency,
accessibility and innovation.
“Open Government Data (OGD) Platform India” (data.gov.in) is a platform for supporting the Open Data initiative
of the Government of India. Large datasets on different projects and parameters are available on the platform.
Let us consider a dataset called “Seasonal and Annual Min/Max Temp Series - India from 1901 to 2017” from the
URL https://data.gov.in/resources/seasonal-andannual-
minmax-temp-series-india-1901-2017.
Our aim is to plot the minimum and maximum temperature and observe the number of times (frequency) a particular
temperature has occurred. We only need toextract the 'ANNUAL - MIN' and 'ANNUAL - MAX' columns from the file.
Also, let us aim to display two Histogram plots:
i) Only for 'ANNUAL - MIN'
ii) For both 'ANNUAL - MIN' and 'ANNUAL - MAX'
Program 4-10
import pandas as pd
import matplotlib.pyplot as plt
#read the CSV file with specified columns
#usecols parameter to extract only two required columns
data=pd.read_csv("Min_Max_Seasonal_IMD_2017.csv", usecols=['ANNUAL - MIN','ANNUAL - MAX'])
df=pd.DataFrame(data)
#plot histogram for 'ANNUAL - MIN'
df.plot(kind='hist',y='ANNUAL - MIN',title='Annual
Minimum Temperature (1901-2017)')
plt.xlabel('Temperature')
plt.ylabel('Number of times')
#plot histogram for both 'ANNUAL - MIN' and #'ANNUAL - MAX'
df.plot(kind='hist',title='Annual Min and Max
Temperature (1901-2017)',color=['blue','red'])
plt.xlabel('Temperature')
plt.ylabel('Number of times')
plt.show()
The Figures 4.11 and 4.12 are produced as output of Program 4-10.
Program 4-11 Plot a frequency polygon for the ‘ANNUAL –MIN’ column of the “Min/Max Temp” data over the
histogram depicting it.
XII – IP (2025.2026 Material & Old CBSE Questions) 137 4.Data Visualisation
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data=pd.read_csv("Min_Max_Seasonal_IMD_2017.csv",
usecols=['ANNUAL - MIN'])
df=pd.DataFrame(data)
#convert the 'ANNUAL - MIN' column into a numpy #1D array
minarray=np.array([df['ANNUAL - MIN']])
# Extract y (frequency) and edges (bins)
y,edges = np.histogram(minarray)
#calculate the midpoint for each bar on the histogram
mid = 0.5*(edges[1:]+ edges[:-1])
df.plot(kind='hist',y='ANNUAL - MIN')
plt.plot(mid,y,'-^')
plt.title('Annual Min Temperature plot(1901 - 2017)')
plt.xlabel('Temperature')
plt.show()
XII – IP – CBSE OLD QUESTIONS
DATA VISUALISATION
1.CBSE BOARD PAPER::2024.25
1. In Python which function of matplotlib library is used to save a plot ?
(A) save() (B) saveplot() (C) export() (D) savefig()
A) (D) savefig()
2. Gurkirat has to fill in the blanks in the given Python program that generates a line plot as shown below.
The given line plot represents the temperature (in degree Celsius) over five days as given in the table :
import ______ as plt # Statement-1
days = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
temp = [30, 32, 31, 29, 28]
plt.__(days, temp) # Statement-2
plt.xlabel('______') # Statement-3
plt.ylabel('Temperature')
plt.title('_____') # Statement-4
plt.show()
Write the missing statements according to the given specifications :
(i) Write the suitable code to import the required module in the blank space in the line marked as Statement-1.
Ans) import matplotlib.pyplot as plt #Statement 1
(ii) Fill in the blank in Statement-2 with a suitable Python function name to create a line plot.
Ans) plt.plot(days,temp) #Statement 2
(iii) Refer to the graph shown and fill in the blank in Statement-3 to display the appropriate label for x-axis.
Ans) plt.xlabel('Days') #Statement 3
(iv) Refer to the graph shown and fill in the blank in Statement-4 to display the suitable chart title.
Ans) plt.title('Temperature over 5 days') #Statement 4
2.CBSE COMPARTMENT PAPER::2024.25
1. Assertion (A) : The Pandas library in Python is primarily used for creating static, animated and
interactive 2D plots or figures.
XII – IP (2025.2026 Material & Old CBSE Questions) 138 4.Data Visualisation
Reason (R) : Data visualization can be achieved with the help of a variety of charts and plots, including
static plots, animations, and interactive visualizations.
(A) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of Assertion (A).
(B) Both Assertion (A) and Reason (R) are true, but Reason (R) is not the correct explanation of
Assertion (A).
(C) Assertion (A) is true, but Reason (R) is false.
(D) Assertion (A) is false, but Reason (R) is true.
Ans) (D) Assertion (A) is false, but Reason (R) is true.
2. Akriti keeps the calorie count of different food items as follows :
Food=['Apple','Banana','Rice','Wheat','Carrot']
Calorie=[72,105,204,455,52]
Write a Python code to generate a Bar Chart on the given data, having suitable Chart Title and labels for X
and Y axis. Also add suitable statement to save this chart with the name calorie.png.
Ans)
import matplotlib.pyplot as plt
Food=['Apple','Banana','Rice','Wheat','Carrot']
Calorie=[72,105,204,455,52]
plt.bar(Food, Calorie)
plt.title("Calorie count of different food items")
plt.xlabel("Food")
plt.ylabel("Calorie")
plt.savefig("calorie.png")
plt.show()
3. Consider the following data :
Write a Python code to draw the following line chart having title and labels for x and y axis as shown below
Also give suitable Python statement to save this chart with name, stud.png.
Ans)
import matplotlib.pyplot as plt
Year=['2019', '2020', '2021', '2022', '2023']
Strength=[150, 180, 240, 120, 180]
plt.plot(Year, Strength)
plt.title("Year Wise Students Strength in Class XII")
plt.xlabel("Year")
plt.ylabel("Student Strength")
plt.savefig("stud.png")
plt.show()
XII – IP (2025.2026 Material & Old CBSE Questions) 139 4.Data Visualisation
3.CBSE SAMPLE PAPER::2024.25
MATPLOTLIB (6 Marks)
2 MCQs & 4 Marks Question
Questions based on Line Chart, Bar Chart, Histogram
7. By default, the plot() function of Matplotlib draws a ______ plot.
(A) histogram (B) column (C) bar (D) line
A) (D) line
18. Which Matplotlib plot is best suited to represent changes in data over time?
(A) Bar plot (B) Histogram (C) Line plot (D) Histogram & Bar plot
A) (C) Line plot
33. During a practical exam, a student Ankita has to fill in the blanks in a Python program that generates a
bar chart. This bar chart represents the number of books read by four students in one month. (4m)
Help Ankita to complete the code.
import _____ as plt #Statement-1
students = ['Karan', 'Lina', 'Raj', 'Simran']
books_read = [12, 9, 5, 3]
plt.bar( students, _____, label='Books Read') #Statement-2
plt.xlabel('Student Name')
plt._____('Books Read') #Statement-3
plt.legend()
plt.title('_____') #Statement-4
plt.show()
I. Write the suitable code for the import statement in the blank space in the line marked as Statement-1.
A) matplotlib.pyplot
II. Refer to the graph shown above and fill in the blank in Statement-2 with suitable Python code.
A) books_read
III. Fill in the blank in Statement-3 with the name of the function to set the label on the y-axis.
A) ylabel
IV. Refer the graph shown above and fill the blank in Statement-4 with suitable Chart Title.
A) Number of Books Read by Students
4.CBSE BOARD PAPER::2023.24
35.a) The inventory management software of a grocery shop stores the price of all fruits as follows:
Fruits=['Apple','Guava','Papaya','Grapes','Mango']
Price=[l50,70,50,30,120]
Write suitable Python code to generate a Bar Chart on the given data. Also add the chart title and
label for X and Y axis. Also add suitable statement to save this chart with the name fruits.png.
A)
import matplotlib.pyplot as plt #Statement 1
Fruits=['Apple','Guava','Papaya','Grapes','Mango'] #Statement 2
Price=[150,70,50,30,120] #Statement 3
plt.bar(Fruits,Price) #Statement 4
XII – IP (2025.2026 Material & Old CBSE Questions) 140 4.Data Visualisation
plt.title("Fruits Prices") #Statement 5
plt.xlabel("Fruits") #Statement 6
plt.ylabel("Price") #Statement 7
plt.savefig("fruits.png") #Statement 8
plt.show() #Statement 9
OR
B) Write suitable Python code to draw the following line chart "CO2 Emission" having title and label
for X and Y axis as shown below.
Also give suitable Python statement to save this chart with the name, emission.png.
A) import matplotlib.pyplot as plt #Statement 1
month=["April", "May", "June", "July", "August"] #Statement 2
percent=[40,50,30,60,20] #Statement 3
plt.plot(month, percent) #Statement 4
plt.title("Month wise CO2 emission") #Statement 5
plt.xlabel("Month") #Statement 6
plt.ylabel("Percentage") #Statement 7
plt.savefig("emission.png") #Statement 8
plt.show() #Statement 9
5.CBSE Additional Practice Paper ::2023.24
5. Which Python command can be utilised to create a histogram using the data in a list named 'values' that represents
scores of students in an exam.
a. plt.hist(values)
b. seaborn.histplot(values)
c. plt.plot_histogram(values)
d. numpy.histogram(values)
32. Wizbiz Corporation is recording the quarterly sales data of its three products through different departments. The
data is as follows:
The company stores this information in a CSV file named "Quarterly_Sales.csv." Mr. Raj is tasked for writing a Python
program to visualise this data. He wrote the following Python code but encountered some difficulties.
Help him by providing solutions to the following situations:
import pandas as pd
import_______________asplt #line1
df=_________________ #line2
df.plot(_________='bar',color=['purple','orange','green, 'yellow']) #line3
plt.title('QuarterlySalesReport') #line4
plt.xlabel('Product')
plt.ylabel('Sales')
plt.show()
i. Choose the correct Python library from the following options to import in line 1:
A. matplotlib B. matplotlib.plot
C. py.plot D. matplotlib.pyplot
XII – IP (2025.2026 Material & Old CBSE Questions) 141 4.Data Visualisation
ii. Choose the correct option to specify the type of graph in line 3: A. type B. kind C. style D. graph
iii. Write suitable python statement to fetch the data from Quarterly_Sales.csv into the datafarme in line 2.
OR
Write Python statement to display total sales done in 'Qtr 1’ and 'Qtr 2’ for each product.
35. District wise total number of houses are represented in the following table:
Draw the following bar graph representing the number of houses in each District (Dist VII, Dist VIII, Dist IX, Dist X).
Also, give suitable python statement to save this chart in E: drive of the computer with name ‘house.png’
OR
Write a python program to plot a line chart based on the given data to depict the weekly study patterns for all the seven
days
Day=[1,2,3,4 ,5,6,7]
Study_Hours =[5 4 6 5,7,8,10]
Also, give suitable python statement to save this chart in d: drive of thecomputer with name ‘study.png’.
CBSE Additional Practice Paper :: 2023.24 (ANSWERS)
5. A
32.i) Ans. D. matplotlib.pyplot
ii) Ans. B. kind
iii) Ans. pd.read_csv('Quarterly_Sales.csv')
(OR Q.Answer) Ans. print(df['Qtr1']+df['Qtr2'])
35. Ans:
import matplotlib.pyplot as plt
district = ['VII','VIII','IX','X']
houses = [40,45,35,44]
plt.bar(district, houses)
plt.savefig('e:\house.png')
plt.show()
(OR Question answer)
Ans.
import matplotlib.pyplot as plt
Day=[1,2,3,4,5,6,7]
Study_Hours=[5,4,6,5,7,8,10]
plt.plot(Day,Study_Hours)
plt.savefig('d:\study.png')
plt.show()
6.CBSE SAMPLE PAPER::2023.24
35. The heights of 10 students of eighth grade are given below:
Height_cms=[145,141,142,142,143,144,141,140, 143,144]
Write suitable Python code to generate a histogram based on the given data, along with an appropriate chart title and
both axis labels. Also give suitable python statement to save this chart.
OR
Write suitable Python code to create 'Favourite Hobby' Bar Chart as shown below:
XII – IP (2025.2026 Material & Old CBSE Questions) 142 4.Data Visualisation
Also give suitable python statement to save this chart.
A) import matplotlib.pyplot as plt #Statement 1 Height_cms=[145,141,142,142,143,.
143,141,140, 143,144] #Statement 2
plt.hist(Height_cms) #Statement 3
plt.title("Height Chart") #Statement 4 plt.xlabel("Height in cms") #Statement 5
plt.ylabel("Number of people") #Statement 6 plt.show() #Statement 7
plt.savefig("heights.jpg")
OR
import matplotlib.pyplot as plt #Statement 1
hobby = ('Dance', 'Music', 'Painting', 'Playing Sports') #Statement 2
users = [300,400,100,500] #Statement 3 plt.bar(hobby, users) #Statement 4
plt.title("Favourite Hobby") #Statement 5 plt.ylabel("Number of people") #Statement 6
plt.xlabel("Hobbies") #Statement 7 plt.show() #Statement 8
plt.savefig("hobbies.jpg")
7.CBSE COMPARTMENT::2022.23
18. Assertion (A): In order to be able to use Python’s data visualization library, we need to import the pyplot module
from matplot library.
Reason (R): The pyplot module houses a variety of functions required to create and customize charts or graphs.
33b) Write a Python code to draw the following bar graph representing the average marks secured by each student in
Term - 2 Exam. Add the Title and Label for
X-axis and Y-axis. Use the following data to draw the graph:
ANSWERS
18. (a) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of Assertion (A).
33b) import matplotlib.pyplot as plt
names = ['ruby','yugesh','Vishesh','Rakesh']
averagemarks=[84,92,45,72]
plt.bar(names,averagemarks)
plt.title("RESULT OF TERM-2 EXAM")
plt.xlabel('STUDENT NAMES')
plt.ylabel('AVERAGE MARKS SCORED')
plt.show()
XII – IP (2025.2026 Material & Old CBSE Questions) 143 4.Data Visualisation
8. CBSE BOARD PAPER::2022.23
12. To compare data values of commission earned by salesmen over a year, which of the following type of graph should
preferably be used?
(i) line (ii) area (iii) bar (iv) scatter
a) (i) or (iii) or (iv)
33. Consider the following graph. Write the Python code to plot it. Also add the Title, label for X and Y axis.
Use the following data for plotting the graph
smarks=[10,40,30,60,55]
sname=["Sahil","Deepak","Anil","Ravi","Riti"]
OR
Write Python code to draw the following bar graph representing the total sales in each quarter. Add the Title, Label for
X-axis and Y-axis.
Use the following data for plotting the graph: sales=[450,300,500,650]
qtr=["QTR1","QTR2","QTR3","QTR4"]
a)import matplotlib.pyplot as plt
smarks=[10,40,30,60,55]
sname=["Sahil","Deepak","Anil","Ravi","Riti"]
plt.plot(sname,smarks)
plt.title("Marks secured by students in Term - 1")
plt.xlabel('Student Name')
plt.ylabel('Marks Scored')
plt.show()
(OR)
import matplotlib.pyplot as plt
#----------------------------#
sales=[450,300,500,650] # ignore as part
qtr=["QTR1","QTR2","QTR3","QTR4"]
#----------------------------#
plt.bar(qtr,sales)
plt.title("Sales each quarter")
plt.xlabel("Quarter")
plt.ylabel("Sales")
plt.show()
9. CBSE SAMPLE PAPER::2022.23
33. Write Python code to plot a bar chart for India’s medal tally as shown below:
XII – IP (2025.2026 Material & Old CBSE Questions) 144 4.Data Visualisation
Also give suitable python statement to save this chart. OR
Write a python program to plot a line chart based on the given data to depict the changing weekly average temperature
in Delhi for four weeks.
Week=[1,2,3,4]
Avg_week_temp=[40,42,38,44]
a) import matplotlib.pyplot as plt
Category=['Gold','Silver','Bronze']
Medal=[20,15,18]
plt.bar(Category,Medal)
plt.ylabel('Medal')
plt.xlabel('Medal Type')
plt.title('Indian Medal tally in Olympics')
plt.show()
Python statement to save the chart:
plt.savefig("aa.jpg")
OR
import matplotlib.pyplot as plt
Week=[1,2,3,4]
Avg_week_temp=[40,42,38,44]
plt.plot(Week,Avg_week_temp)
plt.show()
9. CBSE COMPARTMENT 2021.22
No Questions from Data Visualization
10. CBSE BOARD PAPER::2021.22
8. Which library is imported to draw charts in
Python?
a) csv b) matplotlib c)numpy d) pandas
18. To change the width of bars in a bar chart, which of the following arguments with a float value is used?
a) hwidth b) width c) breadth d)barwidth
20. Which of the following command is used to import matplotlib for coding?
a) import matplotlib.pyplot as plt b) import plt.matplotlib as plt
c) import py.matplotlib as plt d) import pyplot.matplotlib as plt
21. Consider the following statements with reference to Line charts.
Statement A: Line graphs is a tool for comparison and is created by plotting a series of several points and connecting
them with a straight line.
Statement B: You should never use line chart when the chart is in a continuous data set.
a) Statement A is correct.
b) Statement B is correct
c) Statement A is correct but statement B is incorrect
d) Statement A is incorrect, but statement B is correct
22. What is not true about Data Visualization?
a) Graphical representation of information and data.
b) Helps users in analyzing a large amount of data in a simpler way.
c) Data Visualization makes complex data more accessible, understandable, and usable.
d) No library needs to be imported to create charts in Python language.
40. Ms.Kalpana is working with an IT company, and she wants to create charts from the data provided to her.
She generates the following graph:
(Program:
import matplotlib.pyplot as pl
a=[1,2,3,4,5,6,7,8,9,10,11,12]
XII – IP (2025.2026 Material & Old CBSE Questions) 145 4.Data Visualisation
b=[220000,180000,230000,225000,210000,200000,
300000,370000,240000,260000,410000,300000]
pl.plot(a,b,'b',marker='*')
pl.legend(["month number"],loc="upper left")
pl.xlabel("month number")
pl.ylabel("profit in rupees")
pl.title("Company Profit Per Month")
pl.show() )
Which statement is used to mark the line as given in the above fig.:
(a) plt.plot(x,y,marker=’#’,markersize=10, color=’red’, linestyle=’dashdot’)
(b)plt.plot(x,y,marker=’star’,markersize=10, color=’red’)
(c) plt.plot(x,y,marker=’@’,markersize=10, color=’red’, linestyle=’dashdot’)
(d) plt.plot(x,y,marker=’*’,markersize=10, color=’red’)
CBSE QP::2021.22:: PYTHON(T1)::Answers
8b 18b 20a 21c 22d
40d 41c 42d 43a 44b
52a 53a 54c 55d
11. CBSE SAMPLE PAPER :: 2021.22
7. Out of the following, which function cannot be used for customization of charts in Python?
a. xlabel() b. colour() c. title() d. xticks()
8. What is the minimum number of arguments required for plot() function in matplotlib?
a. 1 b. 2 c. 3 d. 4
10. _____________ is the function to save the graph.
a. Savefig() b. Savefigure() c. Savegraph() d. Savechart()
30. Observe the following figure. Identify the coding for obtaining this as output.
a. import matplotlib.pyplot as plt
plt.plot([1,2],[4,5])
plt.show()
b. import matplotlib.pyplot as plt
plt.plot([1,2,3],[4,5,1])
plt.show()
c. import matplotlib.pyplot as plt
plt.plot([2,3],[5,1])
plt.show()
d. import matplotlib.pyplot as plt
plt.plot([1,3],[4,1])
plt.show()
31. Read the statements given below and identify the right option to draw a histogram.
Statement A: To make a Histogram with Matplotlib, we can use the plt.hist() function.
Statement B: The bin parameter is compulsory to create histogram.
a. Statement A is correct
b. Statement B is correct
c. Statement A is correct, but Statement B is incorrect
d. Statement A is incorrect, but Statement B is correct
32. Which graph should be used where each column represents a range of values, and the height of a column corresponds
to how many values are in that range?
a. plot b. line c. bar d. histogram
CBSE SP::2021.22:: PYTHON(T1)::Answers
7. b colour() 8. a. 1 10. a. Savefig() 30. b
31. c. Statement A is correct, but Statement B is incorrect 32. d. histogram
12.CBSE COMPARTMENT 2021
2. Which Python package is used for 2D graphics ?
(A) matplotlib.pyplot (B) pyplot.lib (C) matplotlib.py (D) matplotlib.plt
6. Using Python Matplotlib can be used to display information as a series of data points.
(A) line chart (B) bar graph (C) histogram (D) None of the above
XII – IP (2025.2026 Material & Old CBSE Questions) 146 4.Data Visualisation
36) Consider the following graph. Write the code to plot it. Also label the X and Y axis.
OR
Write code to draw the following bar graph representing the total number of medals won by
Australia.
FOR VISUALLY IMPAIRED
(a) What is Data Visualization ? Discuss briefly. Also mention the name of one of the most commonly used Python
library for data visualization.
Ans) Data visualization is the graphical representation of information and data.
Data visualization is another form of visual art that grabs our interest and keeps our eyes on the message.
Most commonly used Python Library for data visualization is matplotlib
(b) Mention the purpose of the following functions briefly : (i) plot( ) ii) show( ) (iii) savefig( )
Ans) (i) The plot() function draws a line from point to point.The function takes the following parameters for specifying
points in the diagram :
first parameter is an array containing the points on the x-axis the second parameter is an array containing the points on
the y-axis
(ii) The show() function in the pyplot module of matplotlib library is used to display all figures.
(iii) The savefig()method is used to save the figure created after plotting data. The figure created can be saved to our
local machines by using this method.
ANSWERS
2. (A) matplotlib.pyplot 6. (A) line chart
13. 0
2 Banana
3 Mango
36)
import matplotlib.pyplot as plt
X=[1,2,3,4,5]
Y=[12,14,13,15,19]
plt.plot(X,Y)
plt.xlabel('Tests')
plt.ylabel('Marks secured')
plt.show()
OR
import matplotlib.pyplot as plt
X=['Gold','Silver','Bronze','Total']
Y=[75,50,50,200]
plt.bar(X,Y)
plt.xlabel('Medals won by Australia')
plt.ylabel('Medals won')
plt.title('AUSTRALIA MEDAL PLOT')
plt.show()
13.CBSE SAMPLE PAPER 2020.21
2. Fill in the blanks:
The command used to give a heading to a graph is ________
(a) plt.show( ) (b) plt.plot( ) (c) plt.xlabel( ) (d) plt.title( )
XII – IP (2025.2026 Material & Old CBSE Questions) 147 4.Data Visualisation
A) plt.title( )
36. Consider the following graph.
Write the code to plot it.
OR
Draw the following bar graph representing the number of students in each
class.
A) import matplotlib.pyplot as plt
plt.plot([2,7],[1,6])
plt.show()
alternative answer
import matplotlib.pyplot as plt
a = [1,2,3,4,5,6]
b = [2,3,4,5,6,7]
plt.plot (a,b)
OR
import matplotlib.pyplot as plt
Classes = ['VII','VIII','IX','X']
Students = [40,45,35,44]
plt.bar(classes, students)
plt.show()
14.CBSE COMPARTMENT 2020
1.c) Fill in the blank with the correct statement to plot a bar graph using a matplotlib method, so that Company ABC
can see the graphical presentation of its Profit figures for the 2nd quarter of the financial year 2019
(i.e. August, September, October, November).
import matplotlib.pyplot as mtp
Months = ['AUG', 'SEP', 'OCT', 'NOV'] #X Axis
Profits = [125, 220, 230, 175] #Y Axis
_________________________________
mtp.show()
A) mtp.bar(Months, Profits)
1.e) The table below shows the Marks of two students for the four unit tests for academic session 2019-2020. Fill in
the blanks to draw a line graph with Test Names on the X axis and Marks on the Y axis.
import matplotlib.pyplot as plt
Tests = ____________ #Assign Test Names
Rohit = ____________ #Assign Marks of Rohit
Suman = ___________ #Assign Marks of Suman
plt.plot(Tests, Rohit, Suman)
________#Label Y axis as Marks
________#Add legends "Rohit", "Suman" for the lines
plt.show()
A) [‘Unit1’,’Unit2’,’Unit3’,’Unit4’]
[85,88,89,87]
[97,99,90,92]
plt.ylabel(‘Marks’)
plt.legend([‘Rohit’,’Suman’])
XII – IP (2025.2026 Material & Old CBSE Questions) 148 4.Data Visualisation
15.CBSE SAMPLE PAPER 2019.20
1.e) Write a code to plot a bar chart to depict the pass percentage of students in CBSE exams for the years 2015 to 2018
as shown below-
A) import matplotlib.pyplot as plt
import numpy as np
objects=(‘2015’, 2016’, ‘2017’, ‘2018’)
y_pos=np.arrange(len(objects))
percentage=[82,83,85,90]
plt.bar(y_pos, percentage, align=’Centre’,
color=’Blue’)
plt.xticks(y_pos,objects)
plt.ylabel(“Pass Percentage”)
plt.xlabel(‘Years’)
plt.show()
CBSE – QUESTION BANK QUESTIONS
Q.2. Mr. Sharma is working in a game development industry and he was comparing the given chart on
the basis of the rating of the various games available on the play store.
He is trying to write a code to plot the graph. Help Mr. Sharma to fill in the blanks of the code and get the
desired output.
import___________________ #Statement 1
Games=["Subway Surfer","Temple Run",
"Candy Crush","Bottle Shot","Runner Best"]
Rating=[4.2,4.8,5.0,3.8,4.1]
plt.______________(Games,Rating) #Statement 2
plt.xlabel("Games")
plt.______________("Rating") #Statement 3
plt._______________ #Statement 4
i. Choose the right code from the following for statement 1.
i. matplotlib as plt ii. pyplot as plt
iii. matplotlib.pyplot as plt
iv. matplotlib.plt as pyplot
ii. Identify the name of the function that should be used in statement 2 to plot the above graph.
i. line() ii. bar() iii. hist() iv. barh()
iii. Choose the correct option for the statement 3.
i. title("Rating") ii. ytitle("Rating")
iii. ylabel("Rating") iv. yaxis("Rating")
iv. Choose the right function/method from the following for the statement 4.
i. display() ii. print()
iii. bar() iv. show()
v. In case Mr. Sharma wants to change the above plot to the any other shape, which statement, should he change.
i. Statement 1 ii. Statement 2
iii. Statement 3 iv. Statement 4
Answers
i. (iii) ii. (ii) iii. (iii) iv. (iv) v. (ii)
XII – IP (2025.2026 Material & Old CBSE Questions) 149 4.Data Visualisation
Q.12. Gaurav has written a Python Code to create a bar plot as given belowusing the following data :
City Happiness_Index Happy_Index
Male Female
Delhi 60 30
Beijing 40 60
Washington 70 70
Tokyo 65 55
Moscow 85 75
import as ___ #Statement 1
City=['Delhi','Beijing','Washington','Tokyo','Moscow']
Gender=['Male','Female'] Happiness_Index_Male=[60,40,70,65,85]
Happiness_Index_Female=[30,60,70,55,75]
plt.bar([0.25,1.25,2.25,3.25,4.25],Happiness_Index_Male,color='blue',label="Male",width=.5)
plt.([.75,1.75,2.75,3.75,4.75], Happiness_Index_Female,color='Green', width=.5,label="Female") #Statement 2
pos=range(len(City)) print(pos)
plt.xticks(pos,City,fontsize=10)
plt.xlabel('City', fontsize=16)
plt.ylabel('Happiness_Index', fontsize=16)
_______ #Statement 3
_______ #Statement 4
_______ #Statement 5
i. Identify the suitable code to be used in the blank space in line marked as Statement1.
a.matplotlib as plt b.numpy as np
c.pandas as pd d.matplotlib.pyplot as plt
ii. What is the name of the function to plot the required bar graph in the line marked as Statement 2
a. hist() b. pie() c. bar() d. scatter()
iii. Fill in the blank in statement 3 to set Chart Title as “Happiness Index acrosscities by gender
“and font size as 18.
a. plt.xtitle("Happiness Index across cities by gender",fontsize=18)
b. plt.title("Happiness Index across cities by gender",fontsize=18)
c. plt.ytitle("Happiness Index across cities by gender",fontsize=18)
d. plt.show("Happiness Index across cities by gender",fontsize=18)
iv. Identify the suitable code for line marked as Statement 4 to display the legendsas shown in the plot.
a.plt.showlegend() b. plt.legend() c.plt.display() d. plt.show()
v. Fill in the blank marked in Statement 5 to display the plot.
a.plt.plot() b. plt.showplot() c.plt.display() d. plt.show()
Answers
i. d. matplotlib.pyplot as plt ii. c. bar()
iii. b. plt.title("Happiness Index across cities by gender",fontsize=18)
iv. b. plt.legend() v. d. plt.show()
NCERT SUMMARY
• A plot is a graphical representation of a data set which is also interchangeably known as a graph or chart. It is
used to show the relationship between two or more variables.
• In order to be able to use Python’s Data Visualisation library, we need to import the pyplot module from
Matplotlib library using the following statement: import matplotlib.pyplot as plt, where plt is an alias or an
alternative name for matplotlib.pyplot. You can keep any alias of your choice.
• The pyplot module houses functions to create a figure(plot), create a plotting area in a figure, plot lines, bars,
hist. etc., in a plotting area, decorate the plot with labels, etc.
• The various components of a plot are: Title, Legend, Ticks, x label, ylabel
• plt.plot() is used to build a plot, where plt is an alias.
• plt.show() is used to display the figure, where plt is an alias.
• plt.xlabel() and plt.ylabel() are used to set the x and y label of the plot.
XII – IP (2025.2026 Material & Old CBSE Questions) 150 4.Data Visualisation
• plt.title() can be used to display the title of a plot.
• It is possible to plot data directly from the DataFrame.
• Pandas has a built-in .plot() function as part of the DataFrame class.
• The general format of plotting a DataFrame is df.plot(kind = ' ') where df is the name of the DataFrame and
kind can be line, bar, hist, scatter, box depending upon the type of plot to be displayed.
NCERT-EXERCISE
1. What is the purpose of the Matplotlib library?
2. What are some of the major components of any graphs or plot?
3. Name the function which is used to save the plot.
4. Write short notes on different customisation options available with any plot.
5. What is the purpose of a legend?
6. Define Pandas visualisation.
7. What is open data? Name any two websites from which we can download open data.
Note: Give appropriate title, set xlabel and ylabel while attempting the following questions.
10. Plot the following data using a line plot:
• Before displaying the plot display “Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday” in place of
Day 1, 2, 3, 4, 5, 6, 7. • Change the color of the line to ‘Magenta’.
11. Collect data about colleges in Delhi University or any other university of your choice and number of courses they
run for Science, Commerce and Humanities, store it in a CSV file and present it using a bar plot.
14. Collect the minimum and maximum temperature of your city for a month and present it using a histogram plot.
15. Conduct a class census by preparing a questionnaire.
The questionnaire should contain a minimum of five questions. Questions should relate to students, their family
members, their class performance, their health etc. Each student is required to fill up the questionnaire. Compile the
information in numerical terms (in terms of percentage). Present the information through a bar, scatter–diagram.
(NCERT Geography class IX, Page 60)
16. Visit data.gov.in , search for the following in “catalogs” option of the website:
• Final population Totals, India and states
• State Wise literacy rate
Download them and create a CSV file containing population data and literacy rate of the respective state. Also add a
column Region to the CSV file that should contain the values East, West, North and South. Plot a scatter plot for each
region where X axis should be population and Y axis should be Literacy rate. Change the marker to a diamond and size
as the square root of the literacy rate.
Group the data on the column region and display a bar chart depicting average literacy rate for each region.
Think and Reflect:
On providing a single list or array to the plot() function, an matplotlib generate values for both the x and y axis?
***ALL THE BEST DEAR STUDENTS***
XII – IP (2025.2026 Material & Old CBSE Questions) 151 4.Data Visualisation
XII – IP – WORKSHEET 2 (DATAFRAMES) 2025.26
DataFrames – Check List (All Models List)
(1) Introduction Part (Theory) – import, pip, data frames definition and uses, dataframe syntax, others
Questions like differences between Series and DataFrames, etc
(2) Creation (Program/Output)
❖ From a 2D Dictionary having values as lists
❖ From a 2D Dictionary having values as dictionary
❖ From a 2D Dictionary with values as Series Objects
❖ From a list of dictionaries
❖ From a list of lists
❖ From an ND array (1D,2D)
❖ From an existing Dictionary
(Working with index, columns, NaN values, etc)
(3) Dataframe Attributes (and functions)
(4) Operations on DataFrames (loc, iloc, at, iat) – Program/Individual statements/Output
SNo Selecting/Accessing Modifying Adding Deletion
1 Single Column Single Column Single Column Single Column (drop)(del)
2 Multiple Columns Multiple Column Multiple Column
3 Single Row Single Row Single Row Single Row (drop)
4 Multiple Rows Multiple Rows
5 Range of columns Range of columns Deletion of full df (del)
from a range of rows from a range of
rows
6 Single Value Single Value
❖ head( ),tail( ) functions
❖ renaming rows and columns
❖ assign function
❖ Boolean Indexing
❖ Filtering Rows
(5) Iteration – iterrows( ), iteritems( ) – Programs/Outputs
(6) Accessing elements through Slicing
(7) Binary Operations
(8) Question on types of errors
*************
(2) DataFrames Creation
Df
(1) From a 2D dictionary having values as lists: (One of easy method)
import pandas as pd
dict={'RNo':[1,2,3,4],'Name':['Pradeep','Sudeep','Mohan','Pavan'],'Marks':[90,80,95,85]}
df=pd.DataFrame(dict,index=['A','B','C','D'])
print(df)
(2) From a 2D dictionary having values as dictionary:
import pandas as pd
dict={'RNo':{'A':1,'B':2,'C':3,'D':4},'Name':{'A':'Pradeep','B':'Sudeep','C':'Mohan','D':'Pavan'},
'Marks':{'A':90,'B':80,'C':95,'D':85}}
df=pd.DataFrame(dict)
print(df)
XII – Informatics Practices 152 Worksheet 2 (2025.26) - DataFrames
(3) From a 2D dictionary having values as Series objects:
import pandas as pd
R=pd.Series([1,2,3,4])
N=pd.Series(['Pradeep','Sudeep','Mohan','Pavan'])
M=pd.Series([90,80,95,85])
dict={'RNo':R,'Name':N,'Marks':M}
df=pd.DataFrame(dict)
print(df)
Note : In case, index also give while we are creating a datafram, df=pd.DataFrame(dict,index=['A','B','C','D'])
All data will be displayed as NaN
(4) From List of Dictionaries
(Each row details should store as one dictionary, whose keys are column indexes)
import pandas as pd
dict1={'RNo':1,'Name':'Pradeep','Marks':90}
dict2={'RNo':2,'Name':'Sudeep','Marks':80}
dict3={'RNo':3,'Name':'Mohan','Marks':95}
dict4={'RNo':4,'Name':'Pavan','Marks':85}
Stu=[dict1,dict2,dict3,dict4]
df=pd.DataFrame(Stu,index=['A','B','C','D'])
print(df)
(5) From List of Lists (Very easy method)
(Need to take data row wise. Need to give row indexes and column indexes)
import pandas as pd
L=[[1,'Pradeep',90],[2,'Sudeep',80],[3,'Mohan',95],[4,'Pavan',85]]
df=pd.DataFrame(L,index=['A','B','C','D'],columns=['RNo','Name','Marks'])
print(df)
(6) From a 2-D ndarray:
import numpy as np
import pandas as pd
narr=np.array([[1,2,3,4],[90,80,95,85]],np.int32)
df=pd.DataFrame(narr,index=['RNo','Marks'],columns=['S1','S2','S3','S4'])
print(df)
(7) From an existing dataframe:
import pandas as pd
dict={'RNo':[1,2,3,4],'Name':['Pradeep','Sudeep','Mohan','Pavan'],'Marks':[90,80,95,85]}
df=pd.DataFrame(dict,index=['A','B','C','D'])
newdf=pd.DataFrame(df)
print(newdf)
*********
DataFrame Operations (TT)
(1) Create the above DataFrame “TT”
import pandas as pd
D={"P1":["IP","Che","IP"],"P2":["Maths","Phy","Phy"],"P3":["Eng","Acc","Maths"]}
TT=pd.DataFrame(D,index=["Mon","Tue","Wed"])
print(TT)
XII – Informatics Practices 153 Worksheet 2 (2025.26) - DataFrames
(2) Display only the details of First 2 Rows.
TT.head(2) # Using head() method
TT.iloc[0:2] # Using iloc with slicing (index-based selection)
TT.loc[["Mon","Tue"]] # Using loc with index labels
TT[:2] # Using slicing directly on the DataFrame (not recommended for all cases, but works here)
TT.loc["Mon":"Tue"] # It uses label-based slicing in loc, and in Pandas, the end label is inclusive when using loc.
(3) Display the details of rows Wed and Mon (in the order Wed, Mon)
TT.loc[['Wed','Mon']] # Using loc with a list (order maintained):
TT.iloc[[2,0]] # Using iloc by finding their positions manually
TT.reindex(["Wed", "Mon"]) # Using reindex() to reorder explicitly
(4) Display the details of Columns “P1” and “P3”
TT[["P1", "P3"]] # Using double square brackets to specify multiple columns (most common)
TT.loc[:,["P1","P3"]] # Using loc with all rows and selected columns:
TT.iloc[:,[0,2]] # Using iloc if you know the positions of columns:
• "P1" is column 0
• "P3" is column 2
TT.reindex(columns=["P1", "P3"]) # Using reindex on columns:
(5) Display the following output.
we need:
• Rows: "Tue" and "Mon" (in this order)
• Columns: "P3", "P1", and "P2" (in this order)
TT.loc[[“Tue”,”Mon”],[“P3”,”P1”,”P2”]] # Using .loc with both row and column reordering:
TT.iloc[[1, 0], [2, 0, 1]] #Using .iloc with positions:
TT.reindex(index=["Tue", "Mon"], columns=["P3", "P1", "P2"])
#Using .reindex() for rows and columns:
(6) Display the following Output.
Rows: All three in order → ["Mon", "Tue", "Wed"]
Columns: Only ["P3", "P2"]
TT.loc[["Mon", "Tue", "Wed"], ["P3", "P2"]] #Using .loc with label-based indexing:
TT.loc["Mon":"Wed",["P3","P2"]]
TT.loc[:,["P3","P2"]]
TT.iloc[[0, 1, 2], [2, 1]] # Using .iloc with integer positions:
TT.iloc[:,[2,1]]
TT.iloc[0:3,[2,1]]
TT.reindex(index=["Mon", "Tue", "Wed"], columns=["P3", "P2"])
# Using .reindex() with rows and columns:
XII – Informatics Practices 154 Worksheet 2 (2025.26) - DataFrames
(7) Change Tuesday’s 3rd Period to “Eng”
TT.at["Tue","P3"]="Eng" #Using at (fastest for single value assignment):
TT.iat[1,2]="Eng"
TT.loc["Tue", "P3"] = "Eng" #Using loc (label-based selection):
TT.at["Tue", "P3"] = "Eng"
TT.iloc[1, 2] = "Eng" #Using iloc (index-based):
• Row "Tue" is index 1
• Column "P3" is index 2
(8) Add a new column "P4" with values Acc,BS,Maths
TT["P4"]="Acc","BS","Maths"
TT["P4"] = ["Acc", "BS", "Maths"]
TT.loc[:, "P4"] = ["Acc", "BS", "Maths"] #Using .loc with slicing
TT.iloc[:, 3] = ["Acc", "BS", "Maths"] #Using .iloc with column index (if you know index)
TT.at["Mon", "P4"] = "Acc" #Using .at[] for each row
TT.at["Tue", "P4"] = "BS"
TT.at["Wed", "P4"] = "Maths"
TT.loc["Mon", "P4"] = "Acc" # Using .loc[] for each row
TT.loc["Tue", "P4"] = "BS"
TT.loc["Wed", "P4"] = "Maths"
(9) Add a row with index Thu, values Bio,Che,Eng,Acc
TT.loc["Thu"]="Bio","Che","Eng","Acc" # Using .loc[]
TT.loc["Thu"] = ["Bio", "Che", "Eng", "Acc"]
TT.loc["Thu"] = {"P1": "Bio", "P2": "Che", "P3": "Eng", "P4": "Acc"} # Using .loc[] with dictionary
TT.loc["Thu", :] = ["Bio", "Che", "Eng", "Acc"] # Using DataFrame.loc[] with slicing
(10) Rename Mon to Monday
TT.rename(index={"Mon":"Monday"},inplace=True)
TT = TT.rename(index={"Mon": "Monday"})
(11) Rename P2 to Period2
TT.rename(columns={"P2":"Period2"},inplace=True)
TT = TT.rename(columns={"P2": "Period2"})
(12) Delete the Column P3
TT.drop("P3",axis=1,inplace=True)
TT = TT.drop("P3", axis=1)
TT = TT.drop(columns="P3")
del TT["P3"]
XII – Informatics Practices 155 Worksheet 2 (2025.26) - DataFrames
(13) Delete Row with Index "Tue"
TT=TT.drop("Tue")
TT.drop("Tue",inplace=True)
TT.drop("Tue",axis=0,inplace=True)
TT = TT.drop("Tue", axis=0)
TT = TT.drop(index="Tue")
TT = TT.drop(["Tue"])
(14) Modify the Entire P4 values to “Acc”
TT.loc[:,"P4"]="Acc"
TT.iloc[:,1:3]=”Acc”
TT["P4"] = "Acc"
(15) Delete complete DataFrame: del TT
DATAFRAME OPERATIONS – Example2
CREATION:
import pandas as pd
Dict={'RNo':[1,2,3,4],'Name':['Pavan','Mohan','Vanaja','Rani'],'Marks':[85,95,75,78],'Grade':['A','A','B','B']}
DF=pd.DataFrame(Dict, index=['Stu1','Stu2','Stu3','Stu4'])
print(DF)
Operations on DataFrames (loc,iloc,at,iat) – Program/Individual statements/Output
Selecting/Accessing/ Modifying Adding
Displaying
Single to display the column “Name” only DF['Marks']=[70,80,90,85] To add the column
Column DF['Name'] (or) DF.Name DF.Marks=70,80,90,85 “Gender”
DF.loc[:,'Name']
DF.iloc[:,1] # Name and dtype also
DF.loc[:,'Marks']=[70,80,90,85] DF['Gender']=['M','M','F','F']
will be displayed DF.loc[:,'Marks']=70,80,90,85 DF.loc[:,'Gender']=['M','M','F','F']
DF.iloc[:,2]=[70,80,90,85]
DF.iloc[:,[1]] # Name and DF.loc[:,'Gender']='Unknown'
dtype will not be displayed.
DF['Grade']='A'
DF.Grade='A'
DF.iloc[:,3]='A'
Multiple To display columns “Name” to To modify columns “Name” to “Grade”
Columns “Grade”
XII – Informatics Practices 156 Worksheet 2 (2025.26) - DataFrames
DF.loc[:,'Name':'Grade'] DF[['Name','Marks','Grade']]=
DF[['Name','Marks','Grade']] [['Suresh',90,'A'],
DF.iloc[:,1:4] ['Teja',92,'A'],
['Lakshmi',95,'A'],
['Sunita',85,'B']]
(OR)
DF.loc[:,'Name':'Grade']=
To display columns Marks,
[['Suresh',90,'A'],
Name. ['Teja',92,'A'],
DF[['Marks','Name']] ['Lakshmi',95,'A'],
['Sunita',85,'B']]
DF.loc[:,['Marks','Name']]
(OR)
DF.iloc[:,[3,1]] DF.iloc[:,1:4]=
[['Suresh',90,'A'],
['Teja',92,'A'],
['Lakshmi',95,'A'],
['Sunita',85,'B']]
DF.iloc[:,1:4]= 'Student',100,'A'
DF.loc[:,'Name':'Grade']= 'Student',100,'A'
To modify columns Marks,
Name.
DF[['Marks','Name']]=
[[60,'Raj'],[70,'Nani'],
[65,'Indira'],[90,'Lakshmi']]
(Or)
DF.loc[:,['Marks','Name']]=
[[60,'Raj'],[70,'Nani'],
[65,'Indira'],[90,'Lakshmi']]
(Or)
DF.iloc[:,[2,1]]=
[[60,'Raj'],[70,'Nani'],
[65,'Indira'],[90,'Lakshmi']]
DF.loc[:,['Marks','Name']]=95,'Raje
sh'
DF.iloc[:,[2,1]]= 95,'Rajesh'
Single To display ‘Stu2’ details To modify ‘Stu3’ details DF.loc['Stu7']=7,'Rajendra',82
Row DF.loc['Stu2'] DF.loc['Stu3']=[13,'Latha',100,'A'] ,'B'
DF.iloc[1] DF.iloc[2] =[13,'Latha',100,'A']
XII – Informatics Practices 157 Worksheet 2 (2025.26) - DataFrames
(If we try with iloc, we will
get IndexError)
Multipl to display ‘Stu1’ to ‘Stu3’ To modify ‘Stu1’ to ‘Stu3’
e Rows DF.loc['Stu1':'Stu3'] DF.loc['Stu1':'Stu3']=
DF.iloc[0:3] [[1,'Pavani',75,'B'],
[2,'Kumari',92,'A'],
[3,'Anand',95,'A']]
(Or)
DF.iloc[0:3]=[[1,'Pavani',75,'B'],
to display ‘Stu4’,’Stu2’.
[2,'Kumari',92,'A'],[3,'Anand',95,'A']]
DF.loc[['Stu4','Stu2']]
DF.iloc[[3,1]]
To modify ‘Stu4’,’Stu2’.
DF.loc[['Stu4','Stu2']]=
[[10,'Latha',75,'B'],[5,'Hema',92,'A']]
(Or)
DF.iloc[[3,1]]=
[[10,'Latha',75,'B'],[5,'Hema',92,'A']]
Range To display Name and Marks of To modify Name and Marks of
of Pavan, Mohan and Vanaja. Pavan, Mohan and Vanaja.
columns DF.loc['Stu1':'Stu3','Name':'Marks'] DF.loc['Stu1':'Stu3','Name':'Marks']=
from a DF.loc[['Stu1','Stu2','Stu3'],['Name','M
arks']] [['Anand',90],['Manohar',95],
range of
DF.loc['Stu1':'Stu3',['Name','Marks']] ['Revathi',80]] (OR)
rows
DF.loc[['Stu1','Stu2','Stu3'],'Name':'Ma DF.iloc[0:3,1:3] =[['Anand',90],
rks'] ['Manohar',95],['Revathi',80]] (OR)
DF.iloc[0:3,1:3]
DF.loc[['Stu1','Stu2','Stu3'],
['Name','Marks']]=[['Anand',90],
['Manohar',95],['Revathi',80]]
To display Name and Grade of
Mohan and Rani
DF.loc[['Stu2','Stu4'],['Name','Grad
e']] To modify Name and Grade of Mohan
DF.iloc[[1,3],[1,3]] and Rani
DF.loc[['Stu2','Stu4'],
['Name','Grade']]=[['Munna','A'],
['Kanna','A']] (OR)
DF.iloc[[1,3],[1,3]]=
[['Munna','A'],['Kanna','A']]
XII – Informatics Practices 158 Worksheet 2 (2025.26) - DataFrames
Single To display Name of Stu2 To modify Name of Stu2(Mohan to
Value (Mohan) Kumar)
DF.Name['Stu2'] DF.Name['Stu2']=’Kumar’
DF.loc['Stu3','Marks'] DF.Name[3]="Sruthi"
#will display 75 (default index 3, ie Stu4 name will
be changed to Sruthi)
DF.iloc[1,2]
DF.loc['Stu3','Marks']=100
#Will display 95
#vanaja marks will be 100
DF.at['Stu1','RNo'] DF.iloc[1,2]=200
#Display RNo of Stu1 #marks of Mohan to 200
DF.iat[2,1] DF.at['Stu1','RNo']=20
#Display Vanaja #Changes RNo of Stu1 to 20
DF.iat[2,1]='Surabhi
#Changes Name of Stu3
ABOVE DATAFRAME OPERATIONS IN GENERAL FORM
WORKING WITH SINGLE COLUMN
SELECTING/ACCESSING/DISPLAYING:
To display the column “Name” only
DF['Name'] (or) DF.Name (or) DF.loc[:,'Name']
DF.iloc[:,[1]] # Name and dtype will not be displayed.
MODIFYING:
DF['Marks']=[70,80,90,85]
DF.Marks=70,80,90,85
DF.loc[:,'Marks']=[70,80,90,85]
DF.loc[:,'Marks']=70,80,90,85
DF.iloc[:,2]=[70,80,90,85]
DF['Grade']='A'
DF.Grade='A'
DF.iloc[:,3]='A'
XII – Informatics Practices 159 Worksheet 2 (2025.26) - DataFrames
ADDING:
To add the column “Gender”
DF['Gender']=['M','M','F','F']
DF.loc[:,'Gender']=['M','M','F','F']
DF.loc[:,'Gender']='Unknown'
WORKING WITH MULTIPLE COLUMNS
SELECTING/ACCESSING/DISPLAYING:
To display columns “Name” to “Grade”
DF.loc[:,'Name':'Grade']
DF[['Name','Marks','Grade']]
DF.iloc[:,1:4]
To display columns Marks, Name.
DF[['Marks','Name']]
DF.loc[:,['Marks','Name']]
DF.iloc[:,[3,1]]
MODIFYING:
To modify columns “Name” to “Grade”
DF[['Name','Marks','Grade']]=[['Suresh',90,'A'],['Teja',92,'A'],['Lakshmi',95,'A'],['Sunita',85,'B']]
(OR)
DF.loc[:,'Name':'Grade']=[['Suresh',90,'A'],['Teja',92,'A'],['Lakshmi',95,'A'],['Sunita',85,'B']]
(OR)
DF.iloc[:,1:4]=[['Suresh',90,'A'],['Teja',92,'A'],['Lakshmi',95,'A'],['Sunita',85,'B']]
XII – Informatics Practices 160 Worksheet 2 (2025.26) - DataFrames
DF.iloc[:,1:4]= 'Student',100,'A'
DF.loc[:,'Name':'Grade']= 'Student',100,'A'
To modify columns Marks, Name.
DF[['Marks','Name']]=[[60,'Raj'],[70,'Nani'],[65,'Indira'],[90,'Lakshmi']]
(Or)
DF.loc[:,['Marks','Name']]=[[60,'Raj'],[70,'Nani'],[65,'Indira'],[90,'Lakshmi']]
(Or)
DF.iloc[:,[2,1]]=[[60,'Raj'],[70,'Nani'],[65,'Indira'],[90,'Lakshmi']]
DF.loc[:,['Marks','Name']]=95,'Rajesh'
DF.iloc[:,[2,1]]= 95,'Rajesh'
WORKING WITH SINGLE ROW
SELECTING/ACCESSING/DISPLAYING:
To display ‘Stu2’ details
DF.loc['Stu2'] (OR) DF.iloc[1]
MODIFYING:
To modify ‘Stu3’ details
DF.loc['Stu3']=[13,'Latha',100,'A']
DF.iloc[2] =[13,'Latha',100,'A']
ADDING:
DF.loc['Stu7']=7,'Rajendra',82,'B'
(If we try with iloc, we will get IndexError)
WORKING WITH MULTIPLE ROWS
XII – Informatics Practices 161 Worksheet 2 (2025.26) - DataFrames
SELECTING/ACCESSING/DISPLAYING:
To display ‘Stu1’ to ‘Stu3’
DF.loc['Stu1':'Stu3']
DF.iloc[0:3]
To display ‘Stu4’,’Stu2’.
DF.loc[['Stu4','Stu2']]
DF.iloc[[3,1]]
MODIFYING:
To modify ‘Stu1’ to ‘Stu3’
DF.loc['Stu1':'Stu3']=[[1,'Pavani',75,'B'],[2,'Kumari',92,'A'],[3,'Anand',95,'A']]
(Or)
DF.iloc[0:3]=[[1,'Pavani',75,'B'],[2,'Kumari',92,'A'],[3,'Anand',95,'A']]
To modify ‘Stu4’,’Stu2’.
DF.loc[['Stu4','Stu2']]= [[10,'Latha',75,'B'],[5,'Hema',92,'A']]
(Or)
DF.iloc[[3,1]]= [[10,'Latha',75,'B'],[5,'Hema',92,'A']]
RANGE OF COLUMNS FROM RANGE OF ROWS
SELECTING/ACCESSING/DISPLAYING:
To display Name and Marks of Pavan, Mohan and Vanaja.
DF.loc['Stu1':'Stu3','Name':'Marks']
DF.loc[['Stu1','Stu2','Stu3'],['Name','Marks']]
DF.loc['Stu1':'Stu3',['Name','Marks']]
DF.loc[['Stu1','Stu2','Stu3'],'Name':'Marks']
DF.iloc[0:3,1:3]
To display Name and Grade of Mohan and Rani
DF.loc[['Stu2','Stu4'],['Name','Grade']]
DF.iloc[[1,3],[1,3]]
XII – Informatics Practices 162 Worksheet 2 (2025.26) - DataFrames
MODIFYING:
To modify Name and Marks of Pavan, Mohan and Vanaja.
DF.loc['Stu1':'Stu3','Name':'Marks']=[['Anand',90],['Manohar',95],['Revathi',80]] (OR)
DF.iloc[0:3,1:3] =[['Anand',90], ['Manohar',95],['Revathi',80]] (OR)
DF.loc[['Stu1','Stu2','Stu3'],['Name','Marks']]=[['Anand',90],['Manohar',95],['Revathi',80]]
To modify Name and Grade of Mohan and Rani
DF.loc[['Stu2','Stu4'],['Name','Grade']]=[['Munna','A'],['Kanna','A']] (OR)
DF.iloc[[1,3],[1,3]]=[['Munna','A'],['Kanna','A']]
SINGLE VALUE
SELECTING/ACCESSING/DISPLAYING:
To display Name of Stu2 (Mohan)
DF.Name['Stu2']
DF.loc['Stu3','Marks'] #will display 75
DF.iloc[1,2] #will display 95
DF.at['Stu1','RNo'] #Display RNo of Stu1
DF.iat[2,1] #Display Vanaja
MODIFYING:
To modify Name of Stu2(Mohan to Kumar)
DF.Name['Stu2']=’Kumar’
DF.Name[3]="Sruthi" #default index 3, ie Stu4 name will be changed to Sruthi
DF.loc['Stu3','Marks']=100 #vanaja marks will be 100
DF.iloc[1,2]=200 #marks of Mohan to 200
DF.at['Stu1','RNo']=20 #Changes RNo of Stu1 to 20
DF.iat[2,1]='Surabhi #Changes Name of Stu3
Special Case: DataFrame df is a follows:
A B
0 10 20
1 15 25
# Adding new columns based on existing columns
df['E'] = df['A'] + df['B']
df['F'] = df['A'] * df['B']
**************
XII – Informatics Practices 163 Worksheet 2 (2025.26) - DataFrames
OTHER IMPORTANT OPERATIONS
Consider the following DataFrame Veg
import pandas as pd
Dict={'VId':['V1','V2','V3','V4','V5','V6','V7'],'VegName':['Chilly','Onion','Potato','Carrot','Tamota','Garlic','
Cabbage'],'VegPrice':[60,30,40,90,20,120,70]}
Veg=pd.DataFrame(Dict, index=['Veg1','Veg2','Veg3','Veg4','Veg5','Veg6','Veg7'])
print(Veg)
(1) Head and Tail Functions:
Veg.head() - First 5 records
Veg.head(3) - First 3 records
Veg.head(20)
Veg.tail() - Last 5 records will be displayed
Veg.tail(2) - Last 2 records will be displayed
(2) Renaming rows and columns – Change Vid to VegetableId, VegPrice to Vegetable Price, Veg3 to
Vegetable3, Veg5 to Vegetable5.
Veg.rename(index={'Veg3':'Vegetable3','Veg5':'Vegetable5'},columns={'VId':'VegetableID','VegPrice':'Ve
getablePrice'},inplace=True)
XII – Informatics Practices 164 Worksheet 2 (2025.26) - DataFrames
(OR)
Veg.index=['Veg1','Veg2','Vegetable3','Veg4','Vegetable5','Veg6','Veg7']
Veg.columns = ['VegetableID','VegName','VegetablePrice']
(3) Assign function:
Veg=Veg.assign(VId=['One','Two','Three','Four','Five','Six','Seven']) #Vid will be modified
Veg=Veg.assign(Rank=[1,2,3,4,5,6,7]) #As Rank is not available, it will add
Veg=Veg.assign(VId=1)
(4) Deletion of rows and columns
Deletion of a row using Drop:
Veg.drop('Veg5',axis=0,inplace=True)
Veg=Veg.drop('Veg5',axis=0)
Veg=Veg.drop('Veg5')
Veg.drop('Veg5',inplace=True)
Veg = Veg.drop(['Veg1','Veg3','Veg6']) # Deletes the rows with ‘Veg1’,’Veg3’ and ‘Veg6’
# Deleting rows based on a condition
Veg = Veg[Veg['VegPrice'] %6= = 0]# Deletes rows where the value in column Vegprice is other than
multiple of 6 & Stores only multiples of 6
XII – Informatics Practices 165 Worksheet 2 (2025.26) - DataFrames
Deletion of a column using Drop:
Veg.drop('VegName',axis=1,inplace=True)
Veg=Veg.drop('VegName',axis=1)
Veg = Veg.drop(['VId','VegPrice'],axis=1)
Deletion of a column using Del
del Veg['VegName']
Deletion of complete DataFrame using Del:
del Veg #Will deletes full dataframe
(4) Boolean Indexing :
Veg.loc[:,'VegPrice']>50)
Veg.loc[:,'VegPrice']= =90
(5) Filtering Rows:
import pandas as pd
Dict={'Eng':[75,55,40,25],'Mat':[80,90,40,45],'Sci':[10,25,75,90]}
Marks=pd.DataFrame(Dict,index=['Nani','Sudhakar','Kanna','Chinna'])
print(Marks)
XII – Informatics Practices 166 Worksheet 2 (2025.26) - DataFrames
Marks>50
Marks[Marks>50]
Marks[Marks<50]
Marks[Marks%2= =0]
CSV (Comma Separated Values)
Important Models:
Note: If the question is to write statement, only statement is sufficient.
If the question is to write program, should write complete program including import and print statements.
1. Demo Program for importing CSV file (read_csv)
1. Master Balu is a grade XII student, working on CSV files.
He wanted to import details of states and their official languages from a file “States.csv” into a
dataframe ImpLanguages. Note that the file “States.csv” is stored in MyProject folder in E:Drive. Write
a python program for this scenario, also include statement to display the imported dataframe.
import pandas as pd
ImpLanguages=pd.read_csv(“E:\\MyProject\\States.csv”)
print(ImpLanguages)
Note: In the above question, if it is asked to write only statement, second line is sufficient.
To skip first 5 rows ImpLanguages=pd.read_csv(“E:\\MyProject\\States.csv”,skiprows=5)
To skip rows 2 and 5 ImpLanguages=pd.read_csv(“E:\\MyProject\\States.csv”,skiprows=[1,4])
(1 and 4 internally)
To get only first 3 ImpLanguages=pd.read_csv(“E:\\MyProject\\States.csv”,nrows=3)
rows
To get own heading ImpLanguages=pd.read_csv(“E:\\MyProject\\States.csv”,names=[‘Statename’,’Language’])
To say no heading row in ImpLanguages=pd.read_csv(“E:\\MyProject\\States.csv”,header=None)
CSV file
For different ImpLanguages=pd.read_csv(“E:\\MyProject\\States.csv”,sep=’$’)
separator
2. Demo Program for exporting Dataframe to CSV file (to_csv)
Mrs.Kumari has created a DataFrame “Marks” with the following data:
Name Marks
0 Rani 95
1 Pavani 100
2 Sowjanya 92
He wanted to store this DataFrame “Marks” as csv file (friendsmarks.csv) in present python location.
A) Import pandas as pd
Dict={‘Name’:[‘Rani’,’Pavani’,’Sowjanya’],’Marks’:[95,100,92]}
Marks=pd.DataFrame(Dict)
Marks.to_csv(“friendsmarks.csv”)
XII – Informatics Practices 167 Worksheet 2 (2025.26) - DataFrames
XII – IP –MySQL – CONCEPT (2025.26 Material)
Topic 1 – Database Concepts
Revision of database concepts and SQL commands covered in class XI
(Class XI Syllabus: Database concepts and the Structured Query Language.
Database Concepts: Introduction to database concepts and its need, Database Management System.
Relational data model: Concept of domain, tuple, relation, candidate key, primary key, alternate key
Advantages of using Structured Query Language, Data Definition Language, Data Query Language and Data
Manipulation Language, Introduction to MySQL, creating a database using MySQL, Data Types
DATABASE CONCEPTS – REVISION TOUR
DATABASE : A collection of interrelated data stored together to serve multiple applications. It is a computer
based record keeping system.
DBMS: A DBMS refers to database management system.
It is a software that is responsible for storing, manipulating, maintaining and utilizing database.
A database along with a DBMS is referred to as a database management system.
Examples of DBMS Software: MySQL, MS Access, Oracle, MS SQL Server, Sybase, PostgreSQL, SQLite.
Limitations of the File-based Approach:
1. Data Redundancy
2. Data Inconsistency
3. Data Sharing Security/Control Issuesy
4. Difficulty in Access
5. Data Isolation
6. Data Dependence
Purpose/Uses of DBMS:
1. Databases reduces Redundancy.
2. Database controls inconsistency.
3. Database facilitate sharing of data.
4. Database ensures security.
5. Database maintains Integrity
6. Database enforces standards.
Data Redundancy refers to the storage of the same data multiple times (i.e., duplicated data).
Data Inconsistency : Multiple mismatched copies of same data is called data inconsistency.
Data Isolation refers to a situation where data of one file cannot be mapped to other related file in the absence
of links or mappings or common formats.
Data dependence : The close relationship between data stored in files and the software programs that update
and maintain those files is called data dependence.
Database Schema: It is a sketch/skeleton/blueprint of tables, columns, relations, constraints and relationships
that make up a logically distinct section of a database.
Database Instance: It is a snapshot of a database that exists at a particular time, i.e., the data which is stored
in the database at a particular moment of time.
Data Dictionary is a file storing metadata (data about data) of the objects of a database.
Database Constraint: A database constraint is a set of rules that define valid data.
Query is a type of command that retrieves data from a database stored on a server. A database query is usually
written in SQL (Structured Query Language)
Database Engine: It is the underlying software component that a DBMS uses to create, read, update and
delete data from a database.
RELATIONAL DATABASE MODEL
Relational Model was developed by E.F.Codd of the IBM and used widely in the most of the DBMS.
Relation (Table): A Relation or Table is matrix like structure arranged in rows and columns.
It has the following properties:
⮚ In relational database model data is organized into tables (collection of rows and columns).
These tables are also known as relations.
⮚ All items in a column are homogeneous ie same data type.
⮚ Each column assigned a unique name and must have atomic (individual) value.
⮚ All rows of a relation are distinct ie no two identical rows (records) are present in the Relation.
⮚ Ordering of rows (records) or columns (fields) are immaterial.
XII – IP(2025.26) 168 Unit 2 : MySQL
⮚ Domain: It is collection of values from which the value is derived for a column.
⮚ Tuple/Entity/Record: Rows of a table is called as tuple or record.
(Collection of data items which represent a complete unit of information.)
⮚ Attribute/Field : Column of a table is called attribute or field.
⮚ Cardinality : Number of Records(tuples) in a table
⮚ Degree: Number of columns (attributes) in a table.
For example, if we want to store details of students then: Roll, Name, Class, Marks etc will be the
column/attributes and the collection of all the column information will become a row/record.
Roll Name Clas Mark
s s
1 Rajesh VII 75
2 Pavan IX 90
3 Sunitha VIII 80
Table : Student
Here, Degree of the table student = 4 (no.of columns)
Cardinality of the table student = 3 (no.of rows)
Domain of Marks = 0 to 100 (Max.Marks=100)
Data Item: Smallest unit of named data. It represent one type of information and often referred to as a field
or column information.
For the above table,
Cardinality(No.of tuples) is 4,
Degree(Number of attributes) is 3.
KEYS IN A DATABASE
Primary Key: A primary key is a set of one or more attributes that can uniquely identify tuples within the
relation.
Candidate Key: All attribute combinations inside a relation that can serve as primary key are Candidate Keys
as they are candidates for the primary key position.
Alternate Key: A candidate key that is not the primary key is called an Alternate Key.
Foreign Key: A non-key attribute, whose values are derived from the primary key of some other table, is
known as Foreign Key in its current table.
Ex: Student(Admno, Rno,Name,Address,Aadhaar)
Here, Candidate Keys: Admno, Aadhaar
(Selected) Primary Key: Admno
Alternate Key : Aadhaar
Consider Another Table:
Mess (Date, Foodtime,Admno,Price)
In this table Admno is not a primary key but in Student table, it is Primary Key. So Admno in Mess can be a
Foreign Key.
MySQL
Runs on virtually all platforms including Linux, Unix and Windows. Popular for web based application and
online publishing. It is a part of LAMP (Linux, Apache, MySQL, PHP) stack.
It is Free and Open Source Software. It is case insensitive language.
Key features of MySQL:
Speed, Ease of Use, FOSS, Query Language Support, Portability (can work in many platforms), Different
Data Types, Password Security, Can handle large databases, Clients can connect to MySQL Server using
several protocols, Several client and utility programs by MySQL, etc.
Processing Capabilities of SQL:
XII – IP(2025.26) 169 Unit 2 : MySQL
(1) Data Definition Language (DDL): The SQL DDL provides commands for defining relation schemas,
deleting relations, creating indexes, and modifying relation schemas.
(2) Interactive Data Manipulation Language (DML): The SQL DML includes a query language which
includes also commands to insert, delete, and modify tuples in the database.
(3) Embedded Data Manipulation Language: The embedded form of SQL is designed for use within
general purpose programming languages such as Python, C, C++, etc.
(4) Authorization : The SQL DDL includes commands for specifying access rights to relations and views.
(5) Integrity: The SQL provides (limited) forms of integrity checking. Future products and standards of SQL
are likely to include enhanced features for integrity checking.
(6)Transaction Control : SQL includes commands for specifying the beginning and ending of transactions
along with commands to have a control over transaction processing.
CLASSIFICATION OF SQL STATEMENTS
SQL used to interact with database. All SQL statements are instructions to the database only. And that is
where it differs from general purpose programming languages like C or C++ or BASIC, etc.
SQL commands can be divided into following categories.
(i) Data Definition Language (DDL)
(ii) Data Manipulation Language (DML)
(iii) Transaction Control Language (TCL)
(iv) Session Control Commands
(v) System Control Commands
The Data Definition Language (DDL): commands allow you to perform tasks related to data definition.
Create, alter, and drop schema objects: Used to create, change or delete objects such as table, view, index,
etc.
DDL Commands: CREATE TABLE, ALTER TABLE, DROP TABLE, etc
DML (Data Manipulation Language) : Used to manipulate data. That is, DML commands query and
manipulate data in existing schema objects.
Can do:
Retrieval of information stored in the database (select), Insertion of new information into the database (insert
into), Deletion of information from the database (delete from), Modification of data stored in the database
(Update).
Grant and Revoke Privileges and roles: To grant or revoke permissions or privileges to work upon schema
objects. These are also called as Data Control Language (DCL) commands.
Maintenance Commands : To analyse information on a table with an aim of maintaining it.
Ex: ANALYZE TABLE, CHECK TABLE, etc.
DMLs are basically of two types:
(i) Procedural DMLs : Require a user to specify what data is needed and how to get it.
(ii) Non procedural DMLs: Require a user to specify what data is needed without specifying how to get it.
TCL Commands: Transaction is one complete unit of work.
TCL Commands Examples: COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION
CBSE QUESTIONS – QUESTIONS
1. What is a Database Management System (DBMS) ? Mention any two examples of DBMS.
A) A Database Management System(DBMS) is software that lets us store, organize, manage, and retrieve
data efficiently.
Examples: MySQL, PostgreSQL, Microsoft Access, Oracle, Microsoft SQL Server, DB2 and Sybase
2. Assertion (A) and Reason (R) Type question. Choose the correct option as:
(A) Both Assertion (A) and Reason (R) are true, and Reason (R) is the correct explanation of Assertion (A)
(B) Both Assertion (A) and Reason (R) are true, but Reason (R) is not the correct explanation of Assertion (A)
(C) Assertion (A) is True, but Reason (R) is False
(D) Assertion (A) is False, but Reason (R) is True
Assertion (A): In SQL, INSERT INTO is a Data Definition Language (DDL) Command.
Reason (R): DDL commands are used to create, modify, or remove database structures, such as tables.
3. Define the term Primary Key in a database. Explain how it is different from a Candidate Key.
XII – IP(2025.26) 170 Unit 2 : MySQL
A) Primary Key : A set of attributes that can uniquely identify each row in a table (relation). It must contain
unique values and cannot be null.
How it differs from Candidate Key
There can be multiple Candidate Keys in a table (relation), but only one of them is selected as Primary Key.
4. Answer the following questions based on the table Sales given below :
Table : Sales
(i) Suggest the Primary key for the given table ?
A) id
(ii) Is the command “Insert” is a DDL or a DML command ?
A) DML
5. With respect to databases, a row in a relation is also known as a/an __________.
(A) Attribute (B) Tuple (C) Field (D) Domain
6. With respect to databases, a row in a relation is also known as a/an __________.
(A) Attribute (B) Tuple (C) Field (D) Domain
7. The __________ command can be used to select an existing database in SQL.
A) USE
8. Define the term Primary Key in a database. Explain how it is different from a Candidate Key.
A) Primary Key : The attribute(column) or set of attributes that can uniquely identify each row in a table
(relation). It must contain unique values and cannot be null.
How it differs from Candidate Key
There can be multiple Candidate Keys in a table (relation), but only one of them is selected as Primary Key.
9. What do you understand by primary key?
A) The attribute(column) or set of attributes(columns) which is used to identify a tuple/ row uniquely is known
as Primary Key.
Ex: Table : Student
AdmNo Name Marks
1001 Naveen 90
1002 Lakshmi 95
Here Admission Number is primary key as it is identifying a row uniquely.
10. Explain each of the following with illustrations using a table:
1. Candidate Key 2. Primary Key 3. Foreign Key
A) 1. Candidate key : Any attribute which can be used to identify a record in a table.
2. Primary key uniquely identifies a record in the table.
3. Foreign key is an attribute in the table which is the primary key in another table.
For example:
11. Answer the following questions based on the table Sales given below :
Table : Sales
XII – IP(2025.26) 171 Unit 2 : MySQL
Suggest the Primary key for the given table ?
A) id
12. Answer the following questions based on the table Salesman given below :
Table: Salesman
(i) How many tuples does the given table have ?
A) 6
(ii) Suggest the primary key for the given table.
A) salesman_id
13. Consider the following records in Cars table and answer the given questions:
How many tuples are present in the cars table?
Also identify the most suitable column of the cars table to mark as primary key column.
Ans. Number of tuples: 6
Primary key column: CarID
14. Observe the following tables TRANSACTIONS and CUSTOMERS carefully and answer the
questions that follow:
(i) What is the Degree of the table TRANSACTIONS ? What is the cardinality of the table CUSTOMERS ?
(ii) Identify the primary key and candidate keys from the table TRANSACTIONS.
A) i) Degree of the table TRANSACTIONS = 4
Cardinality of the table CUSTOMERS = 3
ii) TNO PRIMARY KEY, CNO CANDIDATE KEYS
15. What is the difference between PRIMARY KEY and UNIQUE constraint applied on Columns of a
table? Explain with the help of example.
A)
PRIMARY KEY UNIQUE
Primary key is used to identify a row (record) in a Unique-key is used to prevent duplicate values in a
table. column.
A table can have only one primary Key. A table can have multiple unique keys.
Primary key does not accept NULL values. Unique key may accept only one NULL value.
Example: Table: Results
Primary key : STUDENTID UNIQUE key: EMAILID
XII – IP(2025.26) 172 Unit 2 : MySQL
16. Consider the following tables SUPPLIER and ITEM and answer the questions that follow:
Table: SUPPLIER
Table : ITEM
Which column should be set as the Primary key for SUPPLIER table? Mr. Vijay, the Database Manager feels
that Email column will not be the right choice for Primary key.
State reason(s) why Email will not be the right choice.
A) Primary key for Supplier table : SNO
Email cannot be set as the primary key as Primary key column cannot be NULL. Many Suppliers may not
have emailids. (OR)
Write the data type and size of INo column of ‘ITEM’ table.
A) Data Type: Char/Varchar Size :3
Topic 2 - SQL
Revision of database concepts and SQL commands covered in class XI (Continuation)
Data Definition: CREATE DATABASE, CREATE TABLE, DROP, ALTER
Data Query: SELECT, FROM, WHERE with relational operators, BETWEEN, logical operators,
IS NULL, IS NOT NULL
Data Manipulation: INSERT, DELETE,UPDATE ) & ALTER TABLE
&
Querying and manipulating data using Group by, Having, Order by.
MySQL – Revision Tour
MySQL Elements:
(1) Literals : It is a fixed data value. It may be of character type or numeric literal or of other datatypes.
Ex: ‘Bvrm’,10,15.5,’marks7’, etc.
(2) Datatypes : To identify the type of data and associated operations for handling it.
Important Datatypes:
Datatype Purpose Other Information
int for integers Ex: 45,-25
float for real values Ex: -2.5, 10.32
Char for characters Fixed length strings
Varchar for characters Variable length strings
Date for dates Format: YYYY-MM-DD
The YEAR data type is used to store a year in a 4-digit format
Characteristics of the YEAR Data Type
Storage: The YEAR data type only requires 1 byte of storage.
Format: Values for the YEAR type can be displayed in YYYY format.
Range: Valid values for the YEAR data type are 1901 to 2155, and 0000.
Differences between char and varchar:
Char has a fixed size, but varchar has a variable size. Char data type stores data of fixed length, whereas the
Varchar data type stores variable format data.
Ex:
Datatype Entered Data Actually stores
XII – IP(2025.26) 173 Unit 2 : MySQL
Char(20) Kishore 20 characters
Varchar(20) Kishore 7 characters
(3) Nulls : If a column in a row has no value, then column is said to be null, or to contain a null.
(4) Comments: A comment is a text that is not executed, it is only for documentation purpose. (Begin with
/* and end with */, Begin with - - followed by space, Begin with # )
Keywords: Words that have a special meaning in SQL.
Commands or Statements are instructions given by you to a SQL database. Commands consist of one or
more logically distinct parts called clauses. Clauses consists of keywords and arguments. Ex: “FROM Sales”,
“WHERE marks>75. Arguments complete or modify the meaning of a clause. Sales is the argument, and
FROM is the keyword of FROM clause. Objects are structures in the database that are given names and
stored in memory.
DATABASE COMMANDS
(1) Creating a Database:
Syntax: Create Database Databasename;
Ex: Create Database WB;
(2) Opening a Database:
Syntax : Use Databasename;
Ex: Use WB;
(3) Getting list of all databases:
Show Databases;
(4) Removing Database:
Syntax: Drop Database Databasename;
Ex: Drop Database WB;
(1) Create Table : This command is used to create a new table.
Syntax: Create Table Tablename (colname datatype(size), colname2 datatype(size),……..);
Example:
CREATE TABLE STUDENT (Rno int,name varchar(30),class varchar(5),DOB date,marks float);
Constraints (Integrity Constraints)
A constraint is a condition or check applicable on a field or set of fields.
Basic Type of Constraints:
(i) Column Constraints:Applicable to one column
(ii) Table Constraints:Applicable to groups
CREATE TABLE SYNTAX WITH CONSTRAINTS:
CREATE TABLE <table name>
( <column name><data type>[(<size>)] <column constraint>,
<column name><data type>[(<size>)] <column constraint>,
……………
<table constraint>(<column name>,[,<column name>…])…);
Ex:
CREATE TABLE employee ( ecode integer NOT NULL, ename char(20) NOT NULL, sex char(1)
NOT NULL, grade char(2), gross decimal );
NOT NULL mean the column can never have empty values (i.e.NULL values).
Otherwise SQL will assume that NULLs are permitted.
Different Constraints:
These constraints ensure database integrity, thus are sometimes called database integrity constraints.
Few of them are:
• Unique Constraint
• Primary Key Constraint
• Default Constraint
• Check Constraint
• Foreign Key Constraint
1. Unique Constraint: This constraint ensures that no two rows have the same value in the specified
column(s).
2. Primary Key Constraint: This constraint declares a column as the primary key of the table. It is similar
to Unique constraint except that the unique
XII – IP(2025.26) 174 Unit 2 : MySQL
constraint can occur multiple times in a table, but primary key constraint can only be applied just once in a
table.
3. Default Constraint: A default value can be specified for a column using the DEFAULT clause. When a
user does not enter a value for the column (having default value), automatically the defined default value is
inserted in the field.
4. Check Constraint: This constraint limits values that can be inserted into a Column of a table.
Ex: CREATE TABLE employee
( ecode integer NOT NULL PRIMARY KEY,
ename char(20) NOT NULL,
sex char(1) NOT NULL,
grade char(2) DEFAULT ‘E1’,
gross decimal CHECK (gross>2000) );
5. Foreign Key Constraint: Whenever two tables are related by a common column (or set of columns), then
the related column(s) in the parent table (or primary table) should be either declared a PRIMARY KEY or
UNIQUE KEY and the related column(s) in the child table (or related table) should have FOREIGN KEY
constraint. Ex: Two Tables…
Items (Itemno, Description, Price, QOH)
Orders (Orderno, Orderdate, Itemno, Qty)
Both the tables are related through common column Itemno. The column Itemno is primary
key in parent table Items and it should be declared foreign key in child table Orders to enforce referential
integrity i.e., both the tables should be created as follows.
CREATE TABLE Items ( Itemno char(5) NOT NULL PRIMARY KEY, ………………..);
CREATE TABLE Orders (Orderno float NOT NULL PRIMARY KEY, …………………Itemno char(5)
REFERENCES Items (Itemno) );
Notice that the related columns Itemno in child table Orders has been declared foreign key through
REFERENCES clause.
CREATING TABLE from Existing Table:
Sno Name Marks
1 Mohan 30
2 Pavan 95
3 Lakshmi 75
4 Sunitha 90
Table : Student
CREATE TABLE PASSSTUDENT AS (SELECT NAME,MARKS FROM Student WHERE Marks>=40);
Sno Name Marks
2 Pavan 95
3 Lakshmi 75
4 Sunitha 90
Table: PASSSTUDENT
(2) Viewing a Table Structure:
This command is used to describe the structure of the table.
Syntax: DESC/DESCRIBE <table name>;
Ex: DESC STUDENT;
(3) SHOW TABLES: This commands is used to show the table names in current database.
Ex: SHOW TABLES;
(4) INSERTING VALUES INTO TABLES:
Syntax: insert into table name values (value1,value2, value3, ….);
Ex: insert into student values(1,'Nani',6,'2011-03-15',75);
XII – IP(2025.26) 175 Unit 2 : MySQL
insert into student values(2,'Mohan',6,'2011-11-23',90), (3,'Lakshmi',6,'2010-10-28',90);
insert into student values(4,'Sunitha',7,'2009-12-15',82), (5,'Naveen',7,'2010-03-20',70);
Note: While entering data quotes should be given for char, varchar & date datatypes.
Inserting Data From Another Table:
Sno Name Marks
1 Mohan 30
2 Pavan 95
3 Lakshmi 75
4 Sunitha 90
Table : Student
INSERT INTO FAILSTUDENT SELECT NAME,MARKS FROM Student WHERE Marks<40;
Sno Name Marks
1 Mohan 30
Table : FAILSTUDENT
(5) SELECT Command: Is used to display the results.
Selecting Particular Columns:
Syntax: Select Att1,Att2,….. (or * to select all data) from tablename;
Ex:
Selecting All Columns:
Syntax: Select * from tablename;
Ex: Select * from student;
Performing calculations in output:
Reordering columns in Query Results: Ex: SELECT CLASS,NAME FROM STUDENT;
(6) DISTINCT: Eliminating Redundant Data (DISTINCT):
By default, data is selected from all the rows of the table. The distinct keyword eliminates duplicate rows
from a result of a select statement.
DISTINCT keyword is used to return only distinct (different) values.
SNo City
1 Bvrm
2 Akd
3 Eluru
4 Hyd
5 Bvrm
Table : CITIES
Ex: SELECT DISTINCT CITY FROM CITIES;
CITY
Bvrm
Akd
Eluru
Hyd
ALL: The keyword ALL gives the results with duplicate values.
Ex: SELECT ALL CITY FROM CITIES;
CITY
Bvrm
XII – IP(2025.26) 176 Unit 2 : MySQL
Akd
Eluru
Hyd
Bvrm
(7) Performing Simple Calculations:
SQL provides dummy table “dual” to do simple calculations.
Ex: SELECT 4*3 FROM DUAL
SELECT 4+3
(8) To get system date:
Example : SELECT CURDATE( )
(9) Scalar Expressions with Selected Fields:
Ex: SELECT salesman_name, comm*100 FROM salesman;
(10) Using Column Aliases:
Ex: SELECT date,type as “Event Type” FROM Event;
(11) Handling Nulls:
The NULL value in a column can be searched for in a table using IS NULL in the WHERE clause.
Ex: SELECT Name,Marks,Address FROM Student WHERE Address IS NULL;
(12) Putting Text in the Query Output:
Ex: SELECT Salesman_name,comm*100,’%’ FROM Salesman;
(13) WHERE Clause – Selecting Specific Rows
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
Syntax: SELECT column1, column2,... FROM table_name WHERE condition;
Ex:
(14) Relational Operators:
To compare two values, a relational operator is used. The result of the comparison is true or false.
They are: =,< >(not equal to), <,<=,>,>=, !=
Ex: SELECT CNAME FROM CITIES WHERE CNAME< >’HYDERABAD’;
(15) Logical Operators:
The logical operators OR(||), AND (&&) and NOT(!) are used to connect search conditions in the WHERE
clause.
Ex: SELECT * FROM EMPLOYEE WHERE DESIGNATION=’CLERK’ OR
DESIGNATION=’MANAGER’;
(16) Condition Based on a Range (Between): Between Keyword is used to select rows which match
criteria between column values. (Both values are including)
SNo City
1 Bvrm
2 Akd
3 Eluru
4 Hyd
5 Bvrm
Table: Cities
XII – IP(2025.26) 177 Unit 2 : MySQL
Ex: SELECT * FROM CITIES WHERE SNO BETWEEN 3 AND 5;
Sno City
3 Eluru
4 Hyd
5 Bvrm
NOT BETWEEN – reverse of BETWEEN
(17) Conditions Based on a List (IN, NOT IN):
SNo City
1 Bvrm
2 Akd
3 Eluru
4 Hyd
5 Bvrm
Table: Cities
Ex: SELECT * FROM CITIES WHERE City in (“Bvrm”,”Eluru”);
Output:
Sno City
1 Bvrm
3 Eluru
5 Bvrm
SELECT * FROM CITIES WHERE City Not In (“Bvrm”,”Eluru”);
SNo City
2 Akd
4 Hyd
(18) Condition Based on Pattern Matching:
String matching operator ‘LIKE’ is for comparison on character strings using patterns.
_ Matches any single character (but must match one character)( not zero characters.)
% Matches zero or more characters.(Any substring)
Ex:
RNo Name
1 Markandeyulu
2 Karun
3 Munna
4 Kalyan
5 Venkat
Table : Student
(A) SELECT * FROM STUDENT WHERE Name LIKE ‘M%’;
Output:
Rno Name
1 Markandeyulu
3 Munna
(B) SELECT * FROM STUDENT WHERE Name LIKE ‘%y%’;
Output:
Rno Name
1 Markandeyulu
4 Kalyan
(C) SELECT * FROM STUDENT WHERE Name LIKE ‘_a%’;
Output:
Rno Name
1 Markandeyulu
2 Karun
4 Kalyan
(19) Operator Precedence:
XII – IP(2025.26) 178 Unit 2 : MySQL
(20) Sorting Results – ORDER BY Clause:
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default.
Keyword to Sort data in Ascending Order - ASC
Keyword to Sort data in Descending Order - DESC
(21) UPDATE & SET : Used to modify data in a table.
Syntax: UPDATE <tablename> SET <columnname=newvalue> [WHERE <predicate>];
Ex: UPDATE STUDENT SET CLASS=8 WHERE NAME='Lakshmi';
UPDATE STUDENT SET MARKS=60 WHERE MARKS=75;
Updating Multiple Columns:
UPDATE Student SET Name=’RajeshBabu’, Marks=90 WHERE Name=’Rajesh;
Using Expressions in Update:
UPDATE Student SET Marks=Marks+5;
UPDATE Employee SET gross=gross*2 WHERE (grade=’E1’ OR grade=’E2’);
Updating to NULL Values:
UPDATE Employee SET Grade=NULL WHERE grade=’E4’;
(22) DELETE FROM: To delete some data from a table.
Syntax: DELETE FROM <tablename> [WHERE <predicate>];
Ex: DELETE FROM STUDENT; (Will delete all records)
DELETE FROM STUDENT WHERE NAME=’Naveen’ (Will delete Naveen’s Record only)
(23) DROP TABLE: To drop a table from the database.
Syntax: DROP TABLE <tablename>;
Ex: DROP TABLE STUDENT;
XII – IP(2025.26) 179 Unit 2 : MySQL
(24) ALTER TABLE:
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
Ex:
create table student(admno int primary key, name varchar(20),marks int);
INSERT INTO STUDENT VALUES(1,'NARESH',90),(2,'MOHAN',85),(3,'LAKSHMI',95);
(A) ALTER TABLE – ADD/ADD Column : To add a column in a table
syntax: ALTER TABLE table_name ADD column_name datatype;
Ex 1: Adding Extra attribute “Gender”.
ALTER TABLE STUDENT ADD GENDER VARCHAR(6); OR
ALTER TABLE STUDENT ADD COLUMN GENDER VARCHAR(6);
Ex 2: Adding Extra attribute “Email”.
ALTER TABLE STUDENTADD Email Varchar(30);
ALTER TABLE STUDENTADD Email Varchar(30);
(B) ALTER TABLE – DROP/DROP COLUMN: To delete a column in a table.
Syntax: ALTER TABLE table_name DROP COLUMN column_name;
The following SQL deletes the "Email" column from the "STUDENT" table:
Example: Deleting attribute “Email”.
ALTER TABLE STUDENT DROP Email; OR
ALTER TABLE STUDENT DROP COLUMN Email;
(C) ALTER TABLE – MODIFY/MODIFY COLUMN: To change the data type of a column
Syntax: ALTER TABLE table_name MODIFY COLUMN column_name datatype;
Example: ALTER TABLE STUDENT MODIFY MARKS FLOAT; OR
ALTER TABLE STUDENT MODIFY COLUMN MARKS FLOAT;
ADD CONSTRAINT
(D) Unique Key Constraint:
Syntax: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE(column_list);
Ex: ALTER TABLE STUDENT ADD CONSTRAINT SplConstraint UNIQUE(Name);
XII – IP(2025.26) 180 Unit 2 : MySQL
(E) Adding a Primary Key in MySQL:
Ex: ALTER TABLE STUDENT ADD PRIMARY KEY(ADMNO);
(F) Adding Check Constraint:
Other Example:
ALTER TABLE employees ADD CONSTRAINT check_last_name
CHECK (last_name IN ('Smith', 'Anderson', 'Jones'));
(G) Adding Foreign Key Constraint:
Syntax: ALTER TABLE table_name ADD FOREIGN KEY (column_name)
REFERENCES table_name(Referencing column_name in table_name);
Other Example:
ALTER TABLE exam ADD FOREIGN KEY(student_id) REFERENCES student(student_id);
DROP CONSTRAINT
The DROP CONSTRAINT command is used to delete a UNIQUE, PRIMARY KEY, FOREIGN KEY, or
CHECK constraint.
(H) DROP a UNIQUE Constraint : To drop a UNIQUE constraint, use the following SQL:
Ex: ALTER TABLE Student DROP CONSTRAINT SplConstrint;
(I)DROP a PRIMARY KEY Constraint: To drop a PRIMARY KEY constraint, use the following
SQL:
Ex: ALTER TABLE Student DROP PRIMARY KEY;
(J)DROP a FOREIGN KEY Constraint: To drop a FOREIGN KEY constraint, use the following
SQL:
Other Ex: ALTER TABLE Orders DROP FOREIGN KEY FK_PersonOrder;
(K)DROP a CHECK Constraint: To drop a CHECK constraint.
Other Ex: ALTER TABLE Persons DROP CHECK CHK_PersonAge;
CBSE QUESTIONS – Questions
1) Write the SQL statement to create a table, Customer with the following specifications :
A) CREATE TABLE Customer (CID INT PRIMARY KEY, FName VARCHAR(20), LName
VARCHAR(20), Age INT ); OR
CREATE TABLE Customer (CID INT , FName VARCHAR(20), LName VARCHAR(20), Age INT ,
PRIMARY KEY (CID) ); OR
CREATE TABLE Customer (CID INT , FName VARCHAR(20), LName VARCHAR(20), Age INT ,
CONSTRAINT PK_CID PRIMARY KEY (CID));
(ii) Write the SQL query to display all records in descending order of LName from the Table Customer.
A) SELECT * FROM Customer ORDER BY LName DESC;
2) Table: SALES. This table records the number of units sold for each product.
XII – IP(2025.26) 181 Unit 2 : MySQL
Write SQL queries for the following:
(i) To delete those records from table SALES whose UnitsSold is less than 80.
A) DELETE FROM SALES WHERE UnitsSold < 80;
3) Table : PRODUCTS. This table stores the basic details of the products available in a shop.
(i) To display the names of all products whose category is not known.
A) SELECT PName FROM PRODUCTS WHERE Category IS NULL;
4) (a) An educational institution is maintaining a database for storing the details of courses being
offered. The database includes a table COURSE with the following attributes :
C_ID : Stores the unique ID for each course.
C_NAME : Stores the course’s name.
INSTRUCTOR : Stores the name of the course instructor.
DURATION : Stores the duration of the course in hours.
Table : COURSE
Write SQL queries for the following :
(i) To add a new record with following specifications :
C_ID : C106
C_NAME : Introduction to AI
INSTRUCTOR : Ms. Preeti
DURATION : 55
A) INSERT INTO COURSE VALUES('C106','INTRODUCTION TO AI', 'MS.PREETI',55); OR
INSERT INTO COURSE (C_ID, C_NAME, INSTRUCTOR, DURATION)
VALUES('C106','INTRODUCTION TO AI','MS.PREETI',55);
5) Table : EMPLOYEE
Write the output of the following SQL Queries :
(i) Select EMP_NAME from EMPLOYEE where SALARY > 60000;
A)
6. The purpose of WHERE clause in a SQL statement is to:
(A) Create a table (B) Filter rows based on a specific condition
(C) Specify the columns to be displayed (D) Sort the result based on a column
A) (B) Filter rows based on a specific condition
7. Identify the SQL command used to delete a relation (table) from a relational database.
(A) DROP TABLE (B) REMOVE TABLE (C) DELETE TABLE (D) ERASE TABLE
A) (A) DROP TABLE
8. State whether the following statement is True or False:
In SQL, the HAVING clause is used to apply filter on groups formed by the GROUP BY clause.
A) True
XII – IP(2025.26) 182 Unit 2 : MySQL
9. Fill in the Blank
The COUNT(*) function provides the total number of __________ within a relation (table) in a relational
database.
(A) Columns (B) Unique values (C) Not-null values (D) Rows
A) (D) Rows
10. Following question is Assertion (A) and Reason (R) Type question. Choose the correct option as:
(A) Both Assertion (A) and Reason (R) are true, and Reason (R) is the correct explanation of Assertion (A)
(B) Both Assertion (A) and Reason (R) are true, but Reason (R) is not the correct explanation of Assertion (A)
(C) Assertion (A) is True, but Reason (R) is False
(D) Assertion (A) is False, but Reason (R) is True
Assertion (A): In SQL, INSERT INTO is a Data Definition Language (DDL) Command.
Reason (R): DDL commands are used to create, modify, or remove database structures, such as tables.
A) (D). Assertion (A) is False, but Reason (R) is True
11. Which MySQL command helps to add a primary key constraint to any table that has already been
created ?
(i) UPDATE (ii) INSERT INTO (iii) ALTER TABLE (iv) ORDER BY
12. Which of the following clause cannot work with SELECT statement in MYSQL ?
(i) FROM (ii) INSERT INTO (iii) WHERE (iv) GROUP BY
13. Which of the following SQL queries is used to retrieve rows from the " customers” table where the "email”
column contains NULL values?
a. SELECT FROM customers WHERE email = NULL;
b. SELECT FROM customers WHERE email IS NOT NULL;
c. SELECT FROM customers WHERE IS NULL(email);
d. SELECT FROM customers WHERE email IS NULL;
14. With reference to SQL, identify the invalid data type.
i. Date ii. Integer iii. Year iv. Month
15. Which type of values will not be considered by SQL while executing the following statement?
SELECT COUNT(column name) FROM inventory;
i. Numeric value ii. text value iii. Null value iv. Date value
16. Which SQL command is used to modify the existing structure of a table?
A) ALTER TABLE
17. Write the names of any two DML commands of SQL.
A) INSERT INTO, UPDATE SET, DELETE FROM
18. Write the command to delete a table STUDENT.
A) DROP TABLE STUDENT
19. The ____________command can be used to makes changes in the rows of a table in SQL.
A) Update
20. The purpose of WHERE clause in a SQL statement is to:
(A) Create a table (B) Filter rows based on a specific condition
(C) Specify the columns to be displayed (D) Sort the result based on a column
21. Identify the SQL command used to delete a relation (table) from a relational database.
(A) DROP TABLE (B) REMOVE TABLE (C) DELETE TABLE (D) ERASE TABLE
22. Write an SQL statement to create a table named STUDENTS, with the following specifications:
A) CREATE TABLE STUDENTS ( StudentID NUMERIC PRIMARY KEY, FirstName VARCHAR(20),
LastName VARCHAR(10), DateOfBirth DATE, Percentage FLOAT(10,2) );
II. Write SQL Query to insert the following data in the Students Table
1, Supriya, Singh, 2010-08-18, 75.5
XII – IP(2025.26) 183 Unit 2 : MySQL
A) INSERT INTO STUDENTS (StudentID, FirstName, LastName, DateOfBirth, Percentage) VALUES (1,
'Supriya', 'Singh', '2010-08-18', 75.5);
23. Consider the following tables:
Table: PAYROLL
(i) List all designations in the decreasing order of Salary
A) SELECT DESIGNATION FROM PAYROLL ORDER BY SALARY DESC;
24. Table: BOOK
IV. Write SQL query to display the Book Code and Price sorted by Price in descending order.
A) SELECT BCODE, PRICE FROM BOOK ORDER BY PRICE DESC;
25. Table: MEDICINE
Write the output of the following SQL Queries.
III. Select MED_NAME from MEDICINE where STOCK between 120 and 200;
26. Consider the table BIKES given below :
Table : BIKES
(a) Write SQL commands for the following :
(i) Display Bikenames and their corresponding Brandnames in descending order of cost.
A) SELECT Bikename, Brandname FROM BIKES ORDER BY Cost DESC;
(ii) Display Brandnames of bikes whose Biketype is not known.
A) SELECT Brandname FROM BIKES WHERE Biketype IS NULL;
(iii) Consider the following query :
SELECT*FROM BIKES WHERE Cost BETWEEN 200000 AND 3000000;
Write another query, using relational and logical operators which will produce the same output.
A) SELECT * FROM BIKES WHERE Cost >= 200000 AND Cost<=3000000;
27. Answer the following questions based on the table Sales given below :
XII – IP(2025.26) 184 Unit 2 : MySQL
Table : Sales
(ii) Write the SQL command to insert the following data in the table Sales :
id E009
Name Sukumar
City Nagpur
Commission 10
A) INSERT INTO Sales VALUES('E009','Sukumar','Nagpur',10) OR
INSERT INTO Sales VALUE('E009','Sukumar','Nagpur',10) OR
INSERT INTO Sales(id, Name, City, Commision) VALUES('E009','Sukumar','Nagpur',10) OR
INSERT INTO Sales(id, Name, City, Commision) VALUE('E009','Sukumar','Nagpur',10)
28. Ms. Sridevi is a placement head in a reputed engineering institute and has created the following table to
store the records of students getting placement in various companies :
Table : Placement
Based on the given table, help Ms. Sridevi to write SQL queries for performing the following tasks :
(i) To list names of those companies where department is either Marketing or Networking.
A) SELECT CompanyName FROM Placement WHERE Department = 'Marketing' OR Department =
'Networking'; OR
SELECT CompanyName FROM Placement WHERE Department IN ('Marketing', 'Networking');
(ii) SELECT CompanyName FROM Placement WHERE Vacancies < 20 AND Appeared >300;
A)
29. Consider the table Faculty and Batch given below :
Table : Faculty
Write SQL queries for the following :
(a) (i) Display name and salary of all faculties in alphabetical order of their names.
A) (i) SELECT FacName,Salary FROM Faculty ORDER BY FacName; OR
SELECT FacName,Salary FROM Faculty ORDER BY FacName ASC;
(ii) Display the details of all faculties whose salary is more than 60000 and have joined before the year 2007.
A) SELECT * FROM Faculty WHERE Salary>60000 AND YEAR(DoJ)<2007; OR
SELECT * FROM Faculty WHERE Salary>60000 AND DoJ<"2007-01-01";
(iii) Increase the salary by 25% of those employees whose qualification is MCA.
A) UPDATE Faculty SET Salary = Salary+(25/100)*Salary WHERE Qualification = "MCA"; OR
UPDATE Faculty SET Salary = Salary*1.25 WHERE Qualification = "MCA";
XII – IP(2025.26) 185 Unit 2 : MySQL
30. Consider the table:
Table : Batch
(i) Delete the records of batches whose subject is English.
A) DELETE FROM Batch WHERE Subject = "English";
31. Write any two differences between DELETE and DROP TABLE command of MySQL.
A)
32. (a) Write an SQL statement to create a table named STUDENTS, with the following specifications:
A) CREATE TABLE STUDENTS (StudentID NUMERIC PRIMARY KEY, FirstName VARCHAR(20),
LastName VARCHAR(10), DateOfBirth DATE, Percentage FLOAT(10,2));
(b). Write SQL Query to insert the following data in the Students Table
1, Supriya, Singh, 2010-08-18, 75.5
A) INSERT INTO STUDENTS (StudentID, FirstName, LastName, DateOfBirth, Percentage) VALUES
(1, 'Supriya', 'Singh', '2010-08-18', 75.5);
33. Consider the following table:
PAYROLL which stores Employee ID (EMP_ID), Department (DEPARTMENT), Designation
(DESIGNATION), and Salary (SALARY) for various employees.
Table: PAYROLL
Write appropriate SQL query to List all designations in the decreasing order of Salary.
A) SELECT DESIGNATION FROM PAYROLL ORDER BY SALARY DESC;
34. Rahul, who works as a database designer, has developed a database for a bookshop. This database includes
a table BOOK whose column (attribute) names are mentioned below:
BCODE: Shows the unique code for each book.
TITLE: Indicates the book’s title.
AUTHOR: Specifies the author’s name.
PRICE: Lists the cost of the book.
Table: BOOK
Write SQL query to display the Book Code and Price sorted by Price in descending order.
A) SELECT BCODE, PRICE FROM BOOK ORDER BY PRICE DESC;
XII – IP(2025.26) 186 Unit 2 : MySQL
35. Dr. Kavita has created a database for a hospital's pharmacy. The database includes a table named
MEDICINE whose column (attribute) names are mentioned below:
MID: Shows the unique code for each medicine.
MED_NAME: Specifies the medicine name
SUPP_CITY: Specifies the city where the supplier is located.
STOCK: Indicates the quantity of medicine available.
DEL_DATE: Specifies the date when the medicine was delivered.
Table: MEDICINE
Write the output of the following SQL Query.
Select MED_NAME from MEDICINE where STOCK between 120 and 200;
A)
36. Write any two differences between DELETE and DROP TABLE command of MySQL.
A)
37. Consider the table BIKES given below :
Table : BIKES
(a) Write SQL commands for the following :
(i) Display Bikenames and their corresponding Brandnames in descending order of cost.
A) SELECT Bikename, Brandname FROM BIKES ORDER BY Cost DESC;
(ii) Display Brandnames of bikes whose Biketype is not known.
A) SELECT Brandname FROM BIKES WHERE Biketype IS NULL;
(iii) Consider the following query :
SELECT*FROM BIKES WHERE Cost BETWEEN 200000 AND 3000000;
Write another query, using relational and logical operators which will produce the same output.
A) SELECT * FROM BIKES WHERE Cost >=200000 AND Cost<=3000000;
38. Answer the following questions based on the table Sales given below :
Table : Sales
XII – IP(2025.26) 187 Unit 2 : MySQL
(i) Write the SQL command to insert the following data in the table Sales :
id E009
Name Sukumar
City Nagpur
Commission 10
A) INSERT INTO Sales VALUES('E009','Sukumar','Nagpur',10) OR
INSERT INTO Sales VALUE('E009','Sukumar','Nagpur',10) OR
INSERT INTO Sales(id, Name, City, Commision) VALUES('E009','Sukumar','Nagpur',10) OR
INSERT INTO Sales(id, Name, City, Commision) VALUE('E009','Sukumar','Nagpur',10)
(ii) Is the command used in part (ii) a DDL or a DML command ?
A) DML
39. Ms. Sridevi is a placement head in a reputed engineering institute and has created the following table to
store the records of students getting placement in various companies :
Table : Placement
Based on the given table, help Ms. Sridevi to write SQL queries for performing the following tasks :
(i) To list names of those companies where department is either Marketing or Networking.
A) SELECT CompanyName FROM Placement WHERE Department = 'Marketing' OR Department =
'Networking'; OR
SELECT CompanyName FROM Placement WHERE Department IN ('Marketing', 'Networking');
(ii) SELECT CompanyName FROM Placement WHERE Vacancies < 20 AND Appeared >300;
A)
40. Consider the tables Faculty and Batch given below :
Table : Faculty
Table : Batch
Write SQL queries for the following :
(i) Display name and salary of all faculties in alphabetical order of their names.
A) SELECT FacName,Salary FROM Faculty ORDER BY FacName; OR
SELECT FacName,Salary FROM Faculty ORDER BY FacName ASC;
(ii) Display the details of all faculties whose salary is more than 60000 and have joined before the year 2007.
A) SELECT * FROM Faculty WHERE Salary>60000 AND YEAR(DoJ)<2007; OR
SELECT * FROM Faculty WHERE Salary>60000 AND DoJ<"2007-01-01";
XII – IP(2025.26) 188 Unit 2 : MySQL
(iii) Increase the salary by 25% of those employees whose qualification is MCA.
A) UPDATE Faculty SET Salary = Salary+(25/100)*Salary WHERE Qualification = "MCA"; OR
UPDATE Faculty SET Salary = Salary*1.25 WHERE Qualification = "MCA";
(iv) Delete the records of batches whose subject is English.
A) DELETE FROM Batch WHERE Subject = "English";
41. Write any two differences between UPDATE and ALTER TABLE commands of MySQL.
UPDATE ALTER TABLE
UPDATE command is used to modify value(s) ●ALTER TABLE command is used to add, delete,
stored in row(s) in a relation. modify, rename attribute(s) in a relation
It is a DML (Data Manipulation Language)
command / UPDATE command performs action on ● It is a DDL(Data Definition Language) command /
data in a table. ALTER TABLE command performs action on the
Example structure of the table.
UPDATE Student SET Marks=30 WHERE ●Example
RollNo = 1; ALTER TABLE Student ADD Email varchar(255);
42. Answer the following question based on the table Salesman given below :
Table: Salesman
Write the MySQL query to display all the records in descending order of commission.
A) SELECT * FROM Salesman order by commission desc;
43. Rupam created a MySQL table to store the details of Nobel prize winners. Help her to write the following
MySQL queries :
Table: NOBEL
(i) Display the names of Nobel Prize winner in 'Literature’ for the year 1970.
A) SELECT WINNER FROM NOBEL WHERE SUBJECT="Literature" AND YEAR = 1970;
(ii) Display the subject and category of winners whose country is not known.
A) SELECT SUBJECT,CATEGORY FROM NOBEL WHERE COUNTRY IS NULL;
(iii) Display the details of all Nobel Prize winners who were Scientists.
A) SELECT * FROM NOBEL WHERE CATEGORY="Scientist";
(iv) Count total number of winners whose subject is Literature.
A) SELECT COUNT(*) FROM NOBEL WHERE SUBJECT="Literature";
44. Consider the following table Employee
XII – IP(2025.26) 189 Unit 2 : MySQL
Write suitable SQL queries to perform the following task :
(i) Change the Department of Shivam to IT in the table Employee.
A) UPDATE Employee SET Department="IT" WHERE First_name="Shivam";
(ii) Remove the record of Alisha from the table Employee.
A) DELETE FROM Employee WHERE First_name="Alisha";
45. Consider the table Reward.
Write a query to remove the table Reward.
A) DROP TABLE Reward;
46. Consider the following records in Cars table and answer the given questions:
(i)Write command for the following To change the color of Model with code as 103 to Green
Ans. UPDATE Cars SET Color = 'Green' WHERE CarID = 103;
(ii)Write the outputs for the following queries:
a. SELECT Make, Model FROM Cars WHERE Price 30000.00;
Ans. Make Model
-------------------
Ford Mustang
BMW X5
-------------------
b. SELECT COUNT(*) AS TotalCars FROM Cars WHERE Year 2022;
Ans. TotalCars
---------
2
---------
c. SELECT CarID, Make, Model FROM Cars where price<22000;
Ans. CarID Make Model
----------------------------
106 Volkswagon Golf
----------------------------
47. Imagine you are assigned a task to manage the inventory of an online store. The store uses an SQL database
to track product information in a table named 'Products.' The 'Products' table has columns for
'ProductID'(PrimaryKey), ‘ProductName', ‘Category’, 'QuantityInStock,' and 'PricePerUnit.'
The following scenarios represent different inventory management tasks:
i) Restocking: Due to a recent sale, the 'QuantityInStock' of a product with 'ProductID' 101, named "Laptop,"
needs to be increased by 10 units.
Ans: UPDATE Products SET QuantityInStock = QuantityInStock + 10 WHERE ProductID = 101;
ii)Product Availability Check: You need to check the availability of a product named "WirelessMouse" in
the 'Electronics' category.
Ans: SELECT * FROM Products WHERE ProductName = 'Wireless Mouse' AND Category = 'Electronics';
iii)ProductUpdate: The price of all products in the 'Electronics' category should be increased by 5% to
account for market changes.
Ans: UPDATE Products SET PricePerUnit = PricePerUnit * 1.05 WHERE Category = 'Electronics';
iv)Out of Stock: Identify and list the products that are currently out of stock (QuantityInStock is 0).
XII – IP(2025.26) 190 Unit 2 : MySQL
Ans: SELECT ProductName FROM Products WHERE QuantityInStock = 0;
For each scenario, provide the SQL statements to perform the necessary action.
48. Based on the SQL table CAR_SALES, write suitable query for the following:
Display the records in the descending order of sales in the second quarter.
A) SELECT * FROM CAR_SALES ORDER BY QT2 DESC;
Predict the output of the following queries based on the table CAR_SALES given above:
SELECT (QT2-QT1)/2 "AVG SALE" FROM CAR_SALES WHERE SEGMENT= "SUV";
A) AVG SALE
13500.0000
6000.0000
49. Write MySQL statements for the following:
i. To create a database named FOOD.
ii. To create a table named Nutrients based on the following specification:
A) i. CREATE DATABASE FOOD;
ii. CREATE TABLE NUTRIENTS (NAME VARCHAR(20) PRIMARY KEY,CALORIES INTEGER);
50. Kabir has created following table named exam:
Help him in writing SQL queries to the perform the following task:
i. Insert a new record in the table having following values: [6,'Khushi','CS',85]
ii. To change the value “IP” to “Informatics Practices” in subject column.
iii. To remove the records of those students whose marks are less than 30 .
iv. To add a new column Grade of suitable datatype.
v. To display records of “Informatics Practices” subject.
Ans: i. INSERT INTO EXAM VALUES(6,'Khushi','CS',85);
ii. UPDATE EXAM SET subject= "Informatics Practices" where subject = "IP";
iii. DELETE FROM EXAM WHERE marks<30;
iv. ALTER TABLE EXAM ADD COLUMN grade varchar(2);
v. Select * from exam where subject="Informatics Practices";
51. Consider the following Table : ITEM :
Table : ITEM
Find the output of the following SQL queries :
(a) SELECT 10+ QTY FROM ITEM WHERE ID = "P1003";
(b) SELECT PRICE*QTY FROM ITEM WHERE QTY < 2;
XII – IP(2025.26) 191 Unit 2 : MySQL
A) (a) 13
(b) 55.00
75.80
52. Consider the Table FURNITURE and write SQL query
To Display all the records in alphabetical order of Item.
A) SELECT * FROM FURNITURE ORDER BY ITEM ;
53. Consider the table HOTEL given below and write any four SQL commands :
Table : HOTEL
(i) Display the details of all the Hotels situated in London.
(ii) Display the details of all 'Deluxe' rooms with price more than 6000 in ascending order of Price.
(iii) Display the Hotel names that end with ''e''.
(iv) Count different types of rooms available in the Hotels.
(v) Display the Hotel names in descending order.
A) i) SELECT * FROM HOTEL WHERE Location = 'London';
(ii) SELECT * FROM HOTEL WHERE Room_type = 'Deluxe' AND Price > 6000 ORDER BY Price;
OR
SELECT * FROM HOTEL WHERE Room_type = 'Deluxe' && Price > 6000 ORDER BY Price;
(iii) SELECT H_Name FROM HOTEL WHERE H_Name LIKE '%e'; OR
SELECT * FROM HOTEL WHERE H_Name LIKE '%e';
(iv) SELECT COUNT(DISTINCT Room_type) FROM HOTEL ;
(v) SELECT H_Name FROM HOTEL ORDER BY H_Name DESC ; OR
SELECT * FROM HOTEL ORDER BY H_Name DESC ;
54) Raunak wanted to display the list of employees who did not get commission. Therefore, he wrote the
following query in SQL :
SELECT emp_name from emp where comm=NULL;
He did not get the correct answer. Identify the error and write the correct SQL statement.
A) SELECT emp_name FROM emp WHERE comm IS NULL;
55) Write the output (i and ii) for the following SQL commands :
Table: F_INDIA
(i) SELECT COUNT (Distinct product) FROM F_INDIA;
XII – IP(2025.26) 192 Unit 2 : MySQL
(ii) SELECT Product, Price FROM F_INDIA WHERE Product LIKE '%m';
A)
(i) COUNT (Distinct product)
5
(ii) Product Price
Sun Cream 678
Beauty Cream 5400
56. Consider the table STUDENT given below:
State the command that will give the output as :
(i). select name from student where class=’XI’ and class=’XII’;
ii. select name from student where not class=’XI’ and class=’XII’;
iii. select name from student where city=”Agra” OR city=”Mumbai”;
iv. select name from student where city IN(“Agra”, “Mumbai”);
Choose the correct option:
a. Both (i) and (ii). b. Both (iii) and (iv).
c. Any of the options (i), (ii) and (iv) d. Only (iii)
A)
(i) b. Both (iii) and (iv)
select name from student where city=”Agra” or city=”Mumbai”; OR
select name from student where city IN (“Agra”, “Mumbai”);
d. Only (iii)
iii. select name from student where city=”Agra” or city=”Mumbai”;
(ii)What will be the output of the following command?
SELECT * FROM STUDENT WHERE GENDER =”F” ORDER BY MARKS;
a.
b.
c.
XII – IP(2025.26) 193 Unit 2 : MySQL
d.
A)
(ii) b.
57. Write SQL queries for (i) to (iii) and the outputs for (iv) and (v), which are based on the
following table PARTICIPANTS
(i) To display details of all PARTICIPANTS of CLASS 10 and 12
A) SELECT * FROM PARTICIPANTS WHERE CLASS IN(10,12); OR
SELECT * FROM PARTICIPANTS WHERE CLASS =10 OR CLASS=12;
(ii) To display the SNAME and CLASS of all PARTICIPANTS in ascending order of their SNAME.
A) SELECT SNAME, CLASS FROM PARTICIPANTS ORDER BY SNAME;
(iii) SELECT DISTINCT EVENT FROM PARTICIPANTS;
A) DISTINCT EVENT
CROSSWORD
DEBATE
QUIZ
58. Shewani has recently started working in MySQL. Help her in understanding the difference between the
following :
(i) Where and having clause
(ii) Count(column_name) and count(*)
A) (i)Where clause is used to show data set for a table based on a condition and having clause is used to put
condition on the result set that comes after using Group by clause.
(ii)COUNT(*) returns the number of items in a group, including NULL values and duplicates.
COUNT(expression) evaluates expression for each row in a group and returns the number of non null values.
Candidate Key – A Candidate Key can be any column or a combination of columns that can qualify as unique
key in database. There can be multiple Candidate Keys in one table. Each Candidate Key can qualify as
Primary Key.
Primary Key – A Primary Key is a column or a combination of columns that uniquely identify a record. Only
one Candidate Key can be Primary Key.
A table can have multiple Candidate Keys that are unique as single column or combined multiple columns to
the table. They are all candidates for Primary Key.
59. On the basis of following table answer the given questions:
Table: CUSTOMER_DETAILS
XII – IP(2025.26) 194 Unit 2 : MySQL
(i) Write the sql query to delete the record of customerManpreet.
(iii) Write the sql query to delete the row from the table where customer has no accumulated amount.
A) (i) DELETE FROM CUSTOMER_DETAILS WHERE CUST_NAME=’Manpreet’;
(iii) Delete from Customer_Details where Accumlt_Amt is NULL;
60. Write commands in SQL for (i) to (iii) and output for (iv) and (v).
Table : Store
(i) To display names of stores along with Sales Amount of those stores that are located in Mumbai.
A) (i) SELECT NAME,SALESAMT FROM STORE WHERE CITY=’MUMBAI’;
(ii) To display the details of store in alphabetical order of name.
A) (ii) SELECT * FROM STORE ORDER BY NAME;
61. Consider the table FANS and answer the following. FANS
Write MySQL queries for the following:
i. To display the details of fans in decending order of their DOB
A) i. SELECT * FROM FANS ORDER BY FAN_DOB DESC;
ii. To display the details of FANS who does not belong to AJMER
A) ii. SELECT * FROM FANS WHERE FAN_CITY < >’AJMER’;
62. In CHAR(10) and VARCHAR(10) , what does the number 10 indicate?
A) It indicates the maximum number of characters that can be stored. It indicates the Size of the column.
63. ‘Employee’ table has a column named ‘CITY’ that stores city in which each employee resides. Write SQL
query to display details of all rows except those rows that have CITY as ‘DELHI’ or ‘MUMBAI’ or
‘CHANDIGARH’.
A) SELECT * FROM Employee WHERE CITY NOT IN
(‘DELHI’,’MUMBAI’,’CHANDIGARH’); OR
SELECT * FROM Employee WHERE CITY <> ‘DELHI’ AND CITY <> ‘MUMBAI’
AND CITY < > ‘CHANDIGARH’ ; OR
SELECT * FROM Employee WHERE NOT CITY IN (‘DELHI’,’MUMBAI’,’CHANDIGARH’);
64. Consider the following table : Table : RESULTS
Abhay wants to know the number of students who took the test. He writes the following SQL statement to
count STUDENTID without duplicates. However the statement is not correct. Rewrite the correct statement.
SELECT DISTINCT (COUNT STUDENTID) FROM RESULTS;
XII – IP(2025.26) 195 Unit 2 : MySQL
A) SELECT COUNT (DISTINCT STUDENTID) FROM RESULTS;
65. Consider the following table ‘Transporter’ that stores the order details about items to be transported. Write
SQL commands for the statements (i) to (viii) and write output for SQL queries (ix) and (x)
Table : TRANSPORTER
(i) To display names of drivers and destination city where TELEVISION is being transported.
(ii) To display driver names and destinations where destination is not MUMBAI.
(iii) To display the names of destination cities where items are being transported.
There should be no duplicate values.
(iv) To display details of rows that have some value in DRIVERGRADE column.
(v) To display names of drivers, names of items and travel dates for those items that are being transported on
or before 1st April 2019.
(vi) To display the number of drivers who have ‘MOHAN’ anywhere in their names.
(vii) To display the names of drivers, item names and travel dates in alphabetic(ascending) order of driver
names.
(viii) To display names of drivers whose names are three characters long
A) (i) SELECT DRIVERNAME, DESTINATION FROM TRANSPORTER WHERE
ITEM="TELEVISION";
(ii) SELECT DRIVERNAME, DESTINATION FROM TRANSPORTER
WHERE DESTINATION <> "MUMBAI"; OR
SELECT DRIVERNAME, DESTINATION FROM TRANSPORTER
WHERE DESTINATION != "MUMBAI"; OR
SELECT DRIVERNAME, DESTINATION FROM TRANSPORTER
WHERE DESTINATION NOT IN ("MUMBAI"); OR
SELECT DRIVERNAME, DESTINATION FROM TRANSPORTER
WHERE NOT DESTINATION = "MUMBAI";
(iii) SELECT DISTINCT(DESTINATION) FROM TRANSPORTER;
(iv) SELECT * FROM TRANSPORTER WHERE DRIVERGRADE IS NOT NULL;
(v) SELECT DRIVERNAME, ITEM, TRAVELDATE FROM TRANSPORTER
WHERE TRAVELDATE <= "2019-04-01";
(vi) SELECT COUNT(DRIVERNAME) FROM TRANSPORTER
WHERE DRIVERNAME LIKE "%MOHAN%" ;
(vii) SELECT DRIVERNAME, ITEM, TRAVELDATE FROM TRANSPORTER
ORDER BY DRIVERNAME;
[ OR ORDER BY DRIVERNAME ASC;]
(viii) SELECT DRIVERNAME FROM TRANSPORTER WHERE DRIVERNAME LIKE "_ _ _"; OR
SELECT DRIVERNAME FROM TRANSPORTER WHERE LENGTH(DRIVERNAME) = 3 ;
66. Mr. Sen has to create a table named ‘Employee’ with Columns to store EmpID, Name, Designation, Age
and Salary.EmpID is the Primary Key and Name cannot be NULL.
Some of the rows that will be inserted are shown below.
101 Smita Kumar Secretary 28 39500.00
102 Mani Scott Programmer 32 45300.00
103 Firdaus Ali Programmer II 45 67500.00
Write SQL query to create the above table with appropriate data types and sizes of columns
A) CREATE TABLE Employee (EmpID INTEGER PRIMARY KEY, Name VARCHAR(20) NOT NULL,
Designation VARCHAR(20), Age INTEGER, Salary DECIMAL(8,2) );
67. Ms.Rajshri is the class teacher of class XII. She wants to create a table named ‘Student' to store marks in
different subjects of her class. Identify any 4 columns for the table along with their suitable data types .
XII – IP(2025.26) 196 Unit 2 : MySQL
A) Admno INT/CHAR / VARCHAR
Name CHAR / VARCHAR
Mark1 DECIMAL / FLOAT / INT / INTEGER
Mark2 DECIMAL / FLOAT / INT / INTEGER
68. Ajay has applied a Constraint on a column(field) such that Ajay will certainly have to insert a value in
this field, when he inserts a new row in the table. Which constraint has Ajay used?
A) NOT NULL constraint
69. ‘STUDENT’ table has a column named ‘REMARK’ that stores Remarks. The values stored in REMARK
are “PASS” or “NOT PASS” or “COMPTT” etc.
Write SQL query to display details of all rows except those that have REMARK as “PASS” .
A) SELECT * FROM student WHERE Remark NOT IN (‘PASS’); OR
SELECT * FROM student WHERE NOT Remark IN (‘PASS’); OR
SELECT * FROM student WHERE Remark <> ‘PASS’; OR
SELECT * FROM student WHERE Remark !=’PASS’; OR
SELECT * FROM student WHERE Remark IN (‘NOT PASS’,’COMPTT’ ) ;
70. Consider the table: ITEM. Write SQL statement to delete the last row.
A) DELETE FROM ITEM WHERE PRODUCTID=105;
71. While creating a table,when a column is declared with data type and size as : DECIMAL(20,6) , how
many maximum number of digits may be present to the right of the decimal point? Which command in SQL
is used to see the structure of the table?
A) 6
DESC / DESCRIBE / SHOW FIELDS FROM <TABLE NAME>;
72. Consider the following table ‘Activity’. Write SQL commands for the statements (i) to(viii) and write
output for SQL queries (ix) and (x).
Table : Activity
(i) To display names of Participants and points in descending order of points.
(ii) To display names and points of participants who have scored points in the range 200 and 300
(both values included).
(iv) To display the names and EVENTDATE of participants who took part in the event anytime in the month
of December of 2018.
(v) To display names of events that have ‘bag’ anywhere in the event names.
(vi) To change the name of Event “Egg&Spoon” to “Lemon&Spoon” everywhere in the table “Activity”
(vii) To display the average POINTS of all the Participants who have got some grade.
(x) SELECT COUNT(DISTINCT POINTS) FROM ACTIVITY;
A) (i) SELECT PARTICIPANT,POINTS FROM Activity ORDER BY POINTS DESC;
XII – IP(2025.26) 197 Unit 2 : MySQL
(ii) SELECT PARTICIPANT,POINTS FROM Activity WHERE POINTS BETWEEN 200 AND 300; OR
SELECT PARTICIPANT,POINTS FROM Activity WHERE POINTS>=200 AND POINTS<=300;
(iv) SELECT PARTICIPANT,EVENTDATE FROM Activity
WHERE EVENTDATE BETWEEN ‘ 2018-12-01 ‘ AND ‘ 2018-12-31 ‘ ; OR
SELECT PARTICIPANT,EVENTDATE FROM Activity
WHERE EVENTDATE>= ‘ 2018-12-01 ‘ AND EVENTDATE<= ‘ 2018-12-31 ‘ ;
(v) SELECT EVENT FROM Activity WHERE EVENT LIKE ‘ %bag% ‘ ;
(vi) UPDATE Activity SET EVENT = ‘Lemon&Spoon’ WHERE EVENT = ‘Egg&Spoon’;
(vii) SELECT AVG(points) FROM Activity WHERE GRADE IS NOT NULL;
(x) COUNT(DISTINCT POINTS)
4
73. Write SQL query to create a table ‘Transporter’ with the following structure:
A) CREATE TABLE Transporter ( OrderlId INTEGER PRIMARY KEY, DriverName VARCHAR(50)
NOT NULL, ItemTransported VARCHAR(50), TravelDate DATE, DestinationCity VARCHAR(50) );
74. What is the purpose of Order By clause in SQL? Explain with the help of suitable example.
A) Order By clause:
The ORDER BY command is used to sort the result set in ascending or descending order.
The following SQL statement displays all the customer’s names in alphabetical order:
SELECT Cname FROM Customers ORDER BY Cname;
ALTER TABLE
1. Consider the Table: Employee
Write suitable SQL query to perform the following task :
Add a new column Experience of integer type in the table Employee.
A) ALTER TABLE Employee ADD Experience int; OR
ALTER TABLE Employee ADD COLUMN Experience int;
2. Suppose you already have “ table in the " database, as described below:
Table Name: Nutrients
Column Name: Food_Item (VARCHAR)
Column Name: Calorie (INT)
Write SQL statements to perform the following tasks:
i. Add a new column named “Plan_Start_Date”(Date) to the "Nutrients" table.
Ans. ALTER TABLE Nutrients ADD Plan_Start_Date DATE;
ii. Modify the "Calorie” column to change its data type to Float.
Ans. ALTER TABLE Nutrients MODIFY Calorie FLOAT;
3. Write SQL command to add a column “COUNTRY” with data type and size as VARCHAR(70) to
the existing table named “PLAYER”. Is it a DDL or DML or TCL command?
A) ALTER TABLE PLAYER ADD COUNTRY VARCHAR(70); It is a DDL command
XII – IP(2025.26) 198 Unit 2 : MySQL
Topic 3
Math functions: POWER (), ROUND (), MOD ().
Text functions: UCASE()/UPPER(), LCASE()/ LOWER(),MID()/SUBSTRING()/SUBSTR (),
LENGTH(), LEFT (), RIGHT (),INSTR(), LTRIM(), RTRIM (), TRIM ().
Date Functions: NOW (), DATE (), MONTH (), MONTHNAME (), YEAR(), DAY(), DAYNAME ().
Aggregate Functions: MAX(), MIN(), AVG (), SUM(), COUNT (); using COUNT (*).
FUNCTIONS IN SQL
A function is used to perform some particular task and it returns zero or more values as a result.
Functions are useful while writing SQL queries also. Functions can be applied to work on single or
multiple records (rows) of a table.
Depending on their application in one or multiple rows, SQL functions are categorised as Single row
functions and Aggregate functions.
Single Row Functions (Scalar functions):
Single row functions are applied on a single value and return a single value.
Figure 1.2 lists different single row functions under three categories — Numeric (Math), String, Date
and Time.
Math functions accept numeric value as input, and return a numeric value as a result. String functions accept
character value as input, and return either character or numeric values as output. Date and time functions
accept date and time values as input, and return numeric or string, or date and time values as output.
(A) NUMERIC FUNCTIONS
Three commonly used numeric functions are POWER()/POW( ), ROUND() and MOD().
Math Functions
Function Description Example with output
POWER(X,Y) can also Calculates X to the power Y. mysql>
be written as POW(X,Y) SELECT POWER(2,3);
Output:
8
ROUND(N,D) Rounds off number N to D number of decimal mysql>SELECT ROUND(2912.564,
places. 1);
Note: If D=0, then it rounds off the number to Output:
the nearest integer. 2912.6
mysql>SELECT ROUND(283.2);
Output:
MOD(A, B) Returns the remainder after dividing number 283
A by mysql>SELECT MOD(21, 2);
number B. Output:
1
Sample Table: Peripherals
SNo PName Cost
1 Keyboard 730
2 Mouse 325
3 Projector 45000
4 Monitor 5600
XII – IP(2025.26) 199 Unit 2 : MySQL
NUMERIC FUNCTIONS
(1) SELECT MOD(11,3);
Note: Prefer this syntax of MOD instead of the following two syntaxes.
(2) SELECT 11%3;
(3) SELECT 11 MOD 3;
(4) SELECT POWER(4,3);
(5) SELECT POW(SNO,3) FROM Peripherals;
(6) SELECT POWER(3.1,2.2);
(7) SELECT ROUND(876.2345,-2);
(8) SELECT ROUND(876.2345,2);
(9) SELECT ROUND(234,0);
(10) SELECT ROUND(234.76767,0);
XII – IP(2025.26) 200 Unit 2 : MySQL
If we write 0 as second argument or leaving second argument, rounds to next integer.
(If first digit after decimal point is 5 or more, 1 will be added in one’s place).
Query Output
SELECT ROUND(589458752.63754827); 589458753
SELECT ROUND(589458752.63754827,0); 589458753
SELECT ROUND(589458752.43754827,0); 589458752
If we write positive value as second argument, those many number of decimal places will come after dot.
Last decimal value depends on next digit.
Query Output
SELECT ROUND(589458752.63754827,1); 589458752.6
SELECT ROUND(589458752.63754827,2); 589458752.64
SELECT ROUND(589458752.63754827,3); 589458752.638
SELECT ROUND(589458752.63754827,3); 589458752.6375
SELECT ROUND(589458752.63754827,3); 589458752.63755
If we write negative value as second argument, those many number of zeros will come in integer part.
Left value to last right most zero depends on the last right most zero’s original value.
Query Output
SELECT ROUND(589458752.63754827,-1); 589458750
SELECT ROUND(589458752.63754827,-2); 589458800
SELECT ROUND(589458752.63754827,-3); 589459000
SELECT ROUND(589458752.63754827,-4); 589460000
SELECT ROUND(589458752.63754827,-5); 589500000
SELECT ROUND(589458752.63754827,-6); 589000000
SELECT ROUND(589458752.63754827,-7); 590000000
SELECT ROUND(589458752.63754827,-8); 600000000
SELECT ROUND(589458752.63754827,-9); 0
(B) STRING FUNCTIONS
String functions can perform various operations on alphanumeric data which are stored in a table. They can
be used to change the case (uppercase to lowercase or vice-versa), extract a substring, calculate the length of
a string and so on.
String Functions
Function Description Example with output
UCASE(string) Converts string into uppercase. mysql> SELECT
OR UCASE(“Informatics Practices”);
UPPER(string) Output:
INFORMATICS PRACTICES
LOWER(string) Converts string into lowercase. mysql> SELECT
OR LOWER(“Informatics Practices”);
LCASE(string) Output:
informatics practices
MID (string, pos, n) Returns a substring of size n mysql> SELECT
OR starting from the specified MID(“Informatics”, 3, 4);
SUBSTRING(string,pos, n) position (pos) of the string. If n is Output:
OR not form
SUBSTR(string, pos, n) specified, it returns the substring mysql> SELECT
from the position pos till end of MID(‘Informatics’,7);
the string. Output:
atics
LENGTH(string) Return the number of characters mysql> SELECT
in the specified string. LENGTH(“Informatics”);
Output:
11
LEFT(string, N) Returns N number of characters mysql> SELECT
from the left side of the string. LEFT(“Computer”, 4);
XII – IP(2025.26) 201 Unit 2 : MySQL
Output:
Comp
RIGHT(string, N) Returns N number of characters mysql> SELECT
from the right side of the string. RIGHT(“SCIENCE”, 3);
Output:
NCE
INSTR(string, substring) Returns the position of the first mysql> SELECT
occurrence of the substring in the INSTR(“Informatics”, “ma”);
given string. Returns 0, if the Output:
substring is not present in the 6
string.
LTRIM(string) Returns the given string after mysql> SELECT LENGTH(“DELHI”),
removing leading white space LENGTH(LTRIM(“DELHI”));
characters. Output:
+--------+
|7|5|
+--------+
RTRIM(string) Returns the given string after mysql>SELECT LENGTH(“PEN “),
removing trailing white space LENGTH(RTRIM(“PEN “));
characters. Output:
+--------+
|5|3|
+--------+
TRIM(string) Returns the given string after mysql> SELECT LENGTH(“ MADAM“),
removing both leading and LENGTH(TRIM(“ MADAM “));
trailing white space characters. Output:
+--------+
|9|5|
+--------+
PRACTICE BITS
Sample Table: Peripherals
SNo PName Cost
1 Keyboard 730
2 Mouse 325
3 Projector 45000
4 Monitor 5600
A.TEXT/STRING FUNCTIONS
Write the output
(1) SELECT LOWER(“My Name is “);
(2) SELECT LCASE(PName) from Peripherals;
(3) SELECT UPPER(“Welcome Dude”);
(4) SELECT UCASE(PName) from Peripherals;
XII – IP(2025.26) 202 Unit 2 : MySQL
(5) SELECT SUBSTR(‘BHIMAVARAM’,2,5);
SELECT SUBSTR(‘BHIMAVARAM’,2); #When there is not third argument, will come till end.
(6) SELECT SUBSTR(‘HYDERABAD’,-7,4);
(7) SELECT SUBSTR(PNAME,2,3) FROM Peripherals WHERE SNo>=2;
(8) SELECT LTRIM(‘ Bhimavaram ‘);
(9) SELECT RTRIM(‘ Bhimavaram ‘);
(10) SELECT TRIM(‘ Bhimavaram ‘);
(11) SELECT TRIM(LEADING ‘ ‘ FROM ‘ Bhimavaram ‘);
(12) SELECT TRIM(TRAILING ‘ ‘ FROM ‘ Bhimavaram ‘);
XII – IP(2025.26) 203 Unit 2 : MySQL
(13) SELECT TRIM(BOTH ‘M’ FROM ‘MMMMMAMARAVATHIMMMMMM’) AS “TRIM”;
(14) SELECT TRIM(LEADING ‘M’ FROM ‘MMMMMAMARAVATHIMMMMMM’) AS “LTRIM”;
(15) SELECT TRIM(TRAILING ‘M’ FROM ‘MMMMMAMARAVATHIMMMMMM’) AS “RTRIM”;
(16) SELECT INSTR(‘AUTOMATIC TELLER MACHINE’,’MA’) AS “ATM”;
(17) SELECT PName,INSTR(Pname,’Mo’) AS “Test Instr” FROM Peripherals;
(18) SELECT LENGTH(‘Bhimavaram’);
(19) SELECT LENGTH(Akiveedu);
(20) SELECT LENGTH(86954);
(21) SELECT LENGTH(7894.11123);
XII – IP(2025.26) 204 Unit 2 : MySQL
(22) SELECT PName, LENGTH(Pname) FROM Peripherals;
(23) SELECT LEFT (“Hiroshima”,4);
(24) SELECT RIGHT(“Hiroshima”,3);
(29) SELECT MID(“Hiroshima”,2,5);
(C) DATE AND TIME FUNCTIONS
There are various functions that are used to perform operations on date and time data. Some of the operations
include displaying the current date, extracting each element of a date (day, month and year), displaying day
of the week and so on.
Date Functions
Function Description Example with output
NOW() It returns the current mysql> SELECT NOW();
system date and time. Output:
2019-07-11 19:41:17
DATE() It returns the date part mysql> SELECT DATE(NOW());
from the given date/ Output:
time expression. 2019-07-11
MONTH(date) It returns the month in mysql> SELECT MONTH(NOW());
numeric form from the Output:
date. 7
MONTHNAME It returns the month mysql> SELECT
(date) name from the specified MONTHNAME(“2003-11-28”);
date. Output:
November
YEAR(date) It returns the year from mysql> SELECT YEAR(“2003-10-03”);
the date. Output:
2003
DAY(date) It returns the day part mysql> SELECT DAY(“2003-03-24”);
from the date. Output:
24
DAYNAME(date) It returns the name of mysql> SELECT
the day from the date. DAYNAME(“2019-07-11”);
Output:
XII – IP(2025.26) 205 Unit 2 : MySQL
Thursday
C.DATE/TIME FUNCTIONS
(1) SELECT NOW();
(2) SELECT DATE(‘2022-12-25 1:12:23’);
(3) SELECT DATE(‘TEST 2022-12-25’);
(4) SELECT DATE(‘2022-12-25 TEST’);
(5) SELECT MONTH(‘2020-05-22’);
(6) SELECT MONTH(‘2022-14-22’);
(7) SELECT MONTH(‘2022-05-22 TESTING’);
(8) SELECT MONTH(‘TESTING 2022-05-22’);
(9) SELECT MONTHNAME(‘1981-04-02’);
XII – IP(2025.26) 206 Unit 2 : MySQL
(10) SELECT MONTHNAME(‘1981-4-02’);
(11)SELECT MONTHNAME(‘WBB 1981-04-02’);
(12) SELECT MONTHNAME(‘1981-04-02 WBB’);
(13) SELECT YEAR(‘2012-05-25’);
(14) SELECT YEAR(‘-3002-03-24’);
(15) SELECT DAY(‘2015-06-26’);
(16) SELECT DAY(‘2015-06-36’);
(17) SELECT DAY(‘WBB 2015-06-15’);
(18) SELECT DAY(‘2015-06-15 WBB’);
XII – IP(2025.26) 207 Unit 2 : MySQL
(19) SELECT DAYNAME(‘2022-09-13’);
(20) Write a query to display the date after 25 days of current date on your system.
(21) SELECT CURDATE() + 15;
AGGREGATE FUNCTIONS:
Aggregate functions are also called multiple row functions.
These functions work on a set of records as a whole, and return a single value for each column of the records
on which the function is applied.
Differences between Single row and Multiple row Functions
Single_row Functions Multiple_row functions
1. It operates on a single row at a time. 1. It operates on groups of rows.
2. It returns one result per row. 2. It returns one result for a group of rows.
3. It can be used in Select, Where, and Order 3. It can be used in the select clause only.
by clause.
4. Math, String and Date functions are 4. Max(), Min(), Avg(), Sum(), Count() and Count(*)
examples of single row functions. are examples of multiple row functions.
Aggregate Functions in SQL
Column must be of numeric type.
Function Description Example with output
MAX Returns the largest value from mysql> SELECT MAX(Price) FROM INVENTORY;
(column) the specified column. Output:
673112.00
MIN Returns the smallest value from mysql> SELECT MIN(Price) FROM INVENTORY;
(column) the specified column. Output:
355205.00
AVG Returns the average of the values mysql> SELECT AVG(Price) FROM INVENTORY;
(column) in the specified column. Output:
576091.625000
SUM Returns the sum of the values mysql> SELECT SUM(Price) FROM INVENTORY;
(column) for the specified column. Output:
4608733.00
COUNT Returns the number of values mysql> SELECT * from MANAGER;
(column) in the specified column ignoring Output:
the NULL values.
Note:
In this example, let us consider
a MANAGER table having two
attributes and four records.
mysql> SELECT COUNT(MEMNAME) FROM
MANAGER;
Output:
XII – IP(2025.26) 208 Unit 2 : MySQL
COUNT(*) Returns the number of records mysql> SELECT COUNT(*) from MANAGER;
in a table. Output:
Note: In order to display the
number of records that matches
a particular criteria in the table,
we have to use COUNT(*) with
WHERE clause.
Sample Table: Peripherals
SNo PName Cost
1 Keyboard 730
2 Mouse 325
3 Projector 45000
4 Monitor 5600
Assume, one more record is added to the peripherals table: ie
5, NULL, 2000
Count : Returns the number of values in the specified column ignoring the NULL values.
So Count(PNAME) will produce 4
Count(SNo) will product 5.
XII – IP(2025.26) 209 Unit 2 : MySQL
Count(*) : Returns the number of records in a table.
MYSQL FUNCTIONS – NCERT MATERIAL
Let us create a database called CARSHOWROOM, having the schema as shown in Figure 1.1.
It has the following four relations:
• INVENTORY: Stores name, price, model, year of manufacturing, and fuel type for each car in inventory of the showroom,
• CUSTOMER: Stores customer Id, name, address, phone number and email for each customer,
• SALE: Stores the invoice number, car Id, customer
id, sale date, mode of payment, sales person’s employee Id, and selling price of the car sold,
• EMPLOYEE: Stores employee Id, name, date of birth, date of joining, designation, and salary of each employee in the showroom.
The records of the four relations are shown in Tables 1.1, 1.2, 1.3, and 1.4 respectively.
Table 1.1 INVENTORY
mysql> SELECT * FROM INVENTORY;
Table 1.3 SALE
mysql> SELECT * FROM SALE;
Table 1.4 EMPLOYEE
mysql> SELECT * FROM EMPLOYEE;
XII – IP(2025.26) 210 Unit 2 : MySQL
NUMERIC FUNCTIONS
Example 1.1 :
In order to increase sales, suppose the car dealer decides to offer his customers to pay the total amount in 10 easy EMIs (equal
monthly installments). Assume that EMIs are required to be in multiples of 10,000. For that, the dealer wants to list the CarID and
Price along with the following data from the Inventory table:
a) Calculate GST as 12% of Price and display the result after rounding it off to one decimal place.
mysql> SELECT ROUND(12/100*Price,1) "GST" FROM INVENTORY;
GST
69913.6
80773.4
68043.7
77743.0
42624.6
78589.7
61680.0
73680.0
b) Add a new column FinalPrice to the table inventory, which will have the value as sum of Price and 12% of the GST.
mysql> ALTER TABLE INVENTORY ADD FinalPrice Numeric(10,1);
mysql> UPDATE INVENTORY SET FinalPrice=Price+Round(Price*12/100,1);
mysql> SELECT * FROM INVENTORY;
c) Calculate and display the amount to be paid each month (in multiples of 1000) which is to be calculated after dividing the
FinalPrice of the car into 10 instalments.
A) SELECT *, ROUND(FinalPrice / 10, -3) AS MonthlyPayment FROM INVENTORY;
d) After dividing the amount into EMIs, find out the remaining amount to be paid immediately, by performing modular
division.
Following SQL query can be used to solve the above mentioned problems:
mysql> select CarId, FinalPrice, ROUND((FinalPrice-MOD(FinalPrice,10000))/10,0)"EMI", MOD(FinalPrice,10000) "Remaining
Amount" FROM INVENTORY;
XII – IP(2025.26) 211 Unit 2 : MySQL
Example 1.2:
a) Let us now add a new column Commission to the SALE table. The column Commission should have a total length of 7 in
which 2 decimal places to be there.
mysql> ALTER TABLE SALE ADD(Commission Numeric(7,2));
b) Let us now calculate commission for sales agents as 12 per cent of the SalePrice, insert the values to the newly added
column Commission and then display records of the table SALE where commission> 73000.
mysql> UPDATE SALE SET Commission=12/100*SalePrice;
mysql> SELECT * FROM SALE WHERE Commission > 73000;
c) Display InvoiceNo, SalePrice and Commission such that commission value is rounded off to 0.
mysql> SELECT InvoiceNo, SalePrice, Round(Commission,0) FROM SALE;
TEXT/STRING FUNCTIONS
Example 1.3
Let us use CUSTOMER relation shown in Table 1.2 to understand the working of string functions.
a) Display customer name in lower case and customer email in upper case from table CUSTOMER.
mysql> SELECT LOWER(CustName), UPPER(Email) FROM CUSTOMER;
LOWER UPPER(Email)
(CustName)
Amitsaha AMITSAHA2@GMAIL.COM
Rehnuma REHNUMA@HOTMAIL.COM
charvinayyar CHARVI123@YAHOO.COM
Gurpreet GUR_SINGH@YAHOO.COM
b) Display the length of the email and part of the email from the email ID before the character ‘@’. Note – Do not print ‘@’.
mysql> SELECT LENGTH(Email), LEFT(Email, INSTR(Email, "@")-1) FROM CUSTOMER;
The function INSTR will return the position of “@” in the email address. So to print email id without “@” we have to use position
-1.
Activity 1.1: Using the table SALE of CARSHOWROOM database, write SQL queries for the following:
a) Display the InvoiceNo and commission value rounded off to zero decimal places.
b) Display the details of SALE where payment mode is credit card.
Activity 1.2 : Using the table INVENTORY from CARSHOWROOM database, write sql queries for the following:
a) Convert the CarMake to uppercase if its value starts with the letter ‘B’.
b) If the length of the car’s model is greater than 4 then fetch the substring starting from position 3 till the end from attribute Model.
c) Let us assume that four digit area code is reflected in the mobile number starting from position number3. For example, 2630 is
the area code of mobile number 4726309212. Now, write the SQL query to display the area code of the customer living in Rohini.
mysql> SELECT MID(Phone,3,4) FROM CUSTOMER WHERE CustAdd like ‘%Rohini%’;
XII – IP(2025.26) 212 Unit 2 : MySQL
MID(Phone,3,4)
1163
d) Display emails after removing the domain name extension “.com” from emails of the customers.
mysql> SELECT TRIM(“.com” from Email) FROM CUSTOMER;
TRIM(".com" FROM Email)
amitsaha2@gmail
rehnuma@hotmail
charvi123@yahoo
gur_singh@yahoo
e) Display details of all the customers having yahoo emails only.
mysql> SELECT * FROM CUSTOMER WHERE Email LIKE "%yahoo%";
DATE/TIME FUNCTIONS
Example 1.4
Let us use the EMPLOYEE table of CARSHOWROOM database to illustrate the working of some of the date and time functions.
a) Select the day, month number and year of joining of all employees.
mysql> SELECT DAY(DOJ), MONTH(DOJ), YEAR(DOJ) FROM EMPLOYEE;
b) If the date of joining is not a Sunday, then display it in the following format "Wednesday, 26, November, 1979."
mysql> SELECT DAYNAME(DOJ), DAY(DOJ), MONTHNAME(DOJ), YEAR(DOJ) FROM EMPLOYEE WHERE
DAYNAME(DOJ)!='Sunday';
Activity 1.4: Using the table EMPLOYEE of CARSHOWROOM database, list the day of birth for all employees whose salary is
more than 25000.
Think and Reflect : Can we use arithmetic operators (+, -. *, or /) on date functions?
AGGREGATE FUNCTIONS
Example 1.5
a) Display the total number of records from table INVENTORY having a model as VXI.
mysql> SELECT COUNT(*) FROM INVENTORY WHERE Model=”VXI”;
b) Display the total number of different types of Models available from table INVENTORY.
mysql> SELECT COUNT(DISTINCT Model) FROM INVENTORY;
c) Display the average price of all the cars with Model LXI from table INVENTORY.
mysql> SELECT AVG(Price) FROM INVENTORY WHERE Model="LXI";
CBSE QUESTIONS – QUESTIONS
1. What will be the output of the following SQL command?
SELECT MONTHNAME('2024-08-02');
(a) 08 (b) 02 (c)February (d)August
XII – IP(2025.26) 213 Unit 2 : MySQL
2. Which of the following is not an aggregate function in SQL?
(a) COUNT(*) (b) MIN( ) (c) LEFT( ) (d) AVG( )
3. State whether the following statement is True or False :
The MOD() function in SQL returns the quotient of division operation between two numbers.
A) False
4. Which SQL function calculates ab?
(a) MOD( ) (b) POWER( ) (c) RAISE( ) (d) ROUND( )
A) POWER( )
5. With respect to SQL, match the function given in column-II with categories given in column-I:
Options :
(A) (i)-(c), (ii)-(d), (iii)-(a), (iv)-(b) (B) (i)-(b), (ii)-(a), (iii)-(d), (iv)-(c)
(C) (i)-(d), (ii)-(b), (iii)-(a), (iv)-(c) (D) (i)-(b), (ii)-(c), (iii)-(d), (iv)-(a)
6. Choose the correct option as :
(A) Both Assertion (A) and Reason (R) are True and Reason (R) is the correct explanation for Assertion (A).
(B) Both Assertion (A) and Reason (R) are True and Reason (R) is not the correct explanation for Assertion (A).
(C) Assertion (A) is True and Reason (R) is False.
(D) Assertion (A) is False, but Reason (R) is True.
Assertion (A) : The ROUND() function in SQL can be used to round off a number to a specified number of
decimal places.
Reason (R) : The ROUND() function is a string function that accepts character values as input and returns
numerical values as output.
A) c
7. Consider the string, "Informatics Practices". Write suitable SQL queries for the following :
(i) To convert the entire string to uppercase.
A) SELECT UCASE("Informatics Practices"); OR
SELECT UPPER("Informatics Practices");
(ii) To display the total number of characters in the given string.
A) SELECT LEN("Informatics Practices"); OR
SELECT LENGTH("Informatics Practices");
8. Table: STUDENTS
(i) Query to find the average age of all students.
A) SELECT AVG(AGE) FROM STUDENTS;
9. Table : COURSE
Write SQL queries for the following :
(i) To display the longest duration among all courses.
A) SELECT MAX(DURATION) FROM COURSE;
(ii) To count total number of courses run by the institution.
A) SELECT COUNT(DISTINCT C_NAME)FROM COURSE;
(iii) To display the instructors’ name in lower case.
A) SELECT LOWER(INSTRUCTOR) FROM COURSE; OR
SELECT LCASE(INSTRUCTOR) FROM COURSE;
XII – IP(2025.26) 214 Unit 2 : MySQL
10. Ashutosh, who is a manager, has created a database to manage employee records. The database
includes a table named EMPLOYEE whose attribute names are mentioned below :
EID : Stores the unique ID for each employee.
EMP_NAME : Stores the name of the employee.
DEPT : Stores the department of the employee.
SALARY : Stores the salary of the employee.
JOIN_DATE : Stores the employee’s joining date.
Table : EMPLOYEE
Write the output of the following SQL Queries :
(i) Select SUBSTRING(EMP_NAME, 1, 5) from EMPLOYEE where DEPT = 'ENGINEERING';
(ii) Select EMP_NAME from EMPLOYEE where month(JOIN_DATE) = 8;
(iii) Select count(DEPT) from EMPLOYEE;
11. (a) Write SQL query for the following:
(i) To display sum total of all the values of the Score column, from STUDENTS
table.
A) SELECT SUM(Score) FROM STUDENTS;
(ii) To display the first five characters of the Name column from STUDENTS
table.
A) SELECT LEFT(Name,5) FROM STUDENTS; OR
SELECT MID(Name,1,5) FROM STUDENTS; OR
SELECT SUBSTRING(Name,1,5) FROM STUDENTS; OR
SELECT SUBSTR(Name,1,5) FROM STUDENTS;
(iii) To display the values of Name column from the STUDENTS table, after removing the trailing spaces.
A) SELECT RTRIM(Name) FROM STUDENTS;
(iv) To retrieve the lowest score from the Score column of GRADES table.
A) SELECT MIN(Score) FROM GRADES;
(v) To increase the fee of all students by 100, in the STUDENTS table. (The name of the column is FEE)
A) UPDATE STUDENTS SET FEE = FEE + 100;
OR
(b) Write SQL queries for the following:
(i) To calculate the square of 15.
A) SELECT POWER(15, 2); OR
SELECT POW(15, 2);
(ii) To round the number 456.789 to the nearest integer.
A) SELECT ROUND(456.789);
(iii) To display the position of first occurrence of 'com' in the string 'mycommercial.com'.
A) SELECT INSTR('mycommercial.com','com');
(iv) To display the name of the day for the date '2024-11-07'.
A) SELECT DAYNAME ('2024-11-07');
(v) To display the current date and time.
A) SELECT NOW(); OR
SELECT SYSDATE();
12. Fill in the Blank
XII – IP(2025.26) 215 Unit 2 : MySQL
The COUNT(*) function provides the total number of __________ within a relation (table) in a relational
database.
(A) Columns (B) Unique values (C) Not-null values (D) Rows
13. Match the following SQL functions/clauses with their descriptions:
(A) P-2, Q-4, R-3, S-1 (B) P-2, Q-4, R-1, S-3
(C) P-4, Q-3, R-2, S-1 (D) P-4, Q-2, R-1, S-3
14. Consider the string: "Database Management System". Write suitable SQL queries for the
following:
I. To extract and display "Manage" from the string.
II. Display the position of the first occurrence of "base" in the given string.
A) I. SELECT SUBSTRING('Database Management System', 10, 6);
II. SELECT INSTR('Database Management System', 'base');
15. Table: ATHLETE
(i) Display the names of all the Indian athletes in uppercase.
A) SELECT UPPER(Name) FROM ATHLETE WHERE COUNTRY = 'INDIA';
16. Rahul, who works as a database designer, has developed a database for a bookshop. This database
includes a table BOOK whose column (attribute) names are mentioned below:
BCODE: Shows the unique code for each book.
TITLE: Indicates the book’s title.
AUTHOR: Specifies the author’s name.
PRICE: Lists the cost of the book.
Table: BOOK
I. Write SQL query to display book titles in lowercase.
A) SELECT LOWER(TITLE) FROM BOOK;
II. Write SQL query to display the highest price among the books.
A) SELECT MAX(PRICE) FROM BOOK;
III. Write SQL query to display the number of characters in each book title.
A) SELECT LENGTH(TITLE) FROM BOOK;
17. Dr. Kavita has created a database for a hospital's pharmacy. The database includes a table named
MEDICINE whose column (attribute) names are mentioned below:
MID: Shows the unique code for each medicine.
MED_NAME: Specifies the medicine name
SUPP_CITY: Specifies the city where the supplier is located.
STOCK: Indicates the quantity of medicine available.
DEL_DATE: Specifies the date when the medicine was delivered.
Table: MEDICINE
XII – IP(2025.26) 216 Unit 2 : MySQL
Write the output of the following SQL Queries.
I. Select LENGTH(MED_NAME) from MEDICINE where STOCK > 100;
A)
II. Select MED_NAME from MEDICINE where month(DEL_DATE) = 4;
A)
III. Select max(DEL_DATE) from MEDICINE;
A)
18. Write suitable SQL query for the following:
I. To display the average score from the test_results column (attribute) in the Exams table
II. To display the last three characters of the registration_number column (attribute) in the Vehicles table.
(Note: The registration numbers are stored in the format DL-01-AV-1234)
III. To display the data from the column (attribute) username in the Users table, after eliminating any leading
and trailing spaces.
IV. To display the maximum value in the salary column (attribute) of the Employees table.
V. To determine the count of rows in the Suppliers table.
A) I. SELECT AVG(test_results) FROM Exams;
II. SELECT RIGHT(registration_number, 3) FROM Vehicles;
III. SELECT TRIM(username) FROM Users;
IV. SELECT MAX(salary) FROM Employees;
V. SELECT COUNT(*) FROM Suppliers;
19. Write suitable SQL query for the following:
I. Round the value of pi (3.14159) to two decimal places.
II. Calculate the remainder when 125 is divided by 8.
III. Display the number of characters in the word 'NewDelhi'.
IV. Display the first 5 characters from the word 'Informatics Practices'.
V. Display details from 'email' column (attribute), in the 'Students' table, after removing any leading and
trailing spaces.
A.
I. SELECT ROUND(3.14159, 2);
II. SELECT MOD(125, 8);
III. SELECT LENGTH('NewDelhi');
IV. SELECT LEFT('Informatics Practices', 5);
V. SELECT TRIM(email) FROM Students;
20. What will be the output of the following query ?
SELECT MOD (5, 15);
(A) 10 (B) 3 (C) 0 (D) 5
XII – IP(2025.26) 217 Unit 2 : MySQL
21. Which of the following aggregate function returns the average of values in a specified column of a
MySQL table ?
(A) AVG(Column) (B) AVERAGE(Column) (C) MEAN(Column) (D) TOTAL(Column)
22. Now() in MySQL returns _______________.
(A) Today’s date (B) Today’s date and current time
(C) System’s date and time (D) Name of active database
23. What will be the output of the following query ?
SELECT SUBSTR("Swachh Survekshan",2,4)
(A) wac (B) wach (C) shan (D) achh
24.What is the output of the following SQL Query ?
SELECT INSTR("KNOWLEDGE","E");
(A) 7 (B) 5 (C) 6 (D) – 6
25. Consider the string 'PAINTING'. Write the SQL commands to display the following output :
(i) ING (ii) INT
A) (i) SELECT RIGHT('PAINTING',3); OR
SELECT SUBSTR('PAINTING',6,3); OR
SELECT SUBSTRING('PAINTING',6,3); OR
SELECT MID('PAINTING',6,3);
(ii) SELECT SUBSTR('PAINTING',3,3); OR
SELECT SUBSTRING('PAINTING',3,3); OR
SELECT MID('PAINTING',3,3);
26. Consider the table BIKES given below :
Table : BIKES
(b) Predict the output of the following queries based on the table BIKES given above :
(i) SELECT UCASE(TRIM(Brandname)) FROM
BIKES WHERE Bid = 1003;
(ii) SELECT COUNT(Biketype) FROM BIKES;
(iii) SELECT SUM(Cost), Brandname FROM BIKES GROUP BY Brandname Having Brandname =
"WMV" OR Brandname = "Indiana";
A)
(i) INDIANA
(ii) 9
(iii)
27. Ms. Sridevi is a placement head in a reputed engineering institute and has created the following table to
store the records of students getting placement in various companies : Table : Placement
Based on the given table, help Ms. Sridevi to write SQL queries for performing the following tasks :
(ii) To display the joining month name for Rising Star company.
XII – IP(2025.26) 218 Unit 2 : MySQL
Ms. Sridevi has written following queries. Write the output of each query :
A) SELECT MONTHNAME(DoJ) FROM Placement WHERE CompanyName = 'Rising Star';
(iii) SELECT LEFT (CompanyName, INSTR(CompanyName,"R")) FROM Placement where vacancies
>=20;
A)
SECTION – E
28. Consider the tables Faculty and Batch given below : Table : Faculty
Table : Batch
Write SQL queries for the following :
(a) (ii) Display details of faculties who joined on Monday.
A) SELECT * FROM Faculty WHERE DAYNAME(DoJ)=’Monday’; OR
SELECT * FROM Faculty WHERE DAYOFWEEK(DoJ)=2;
(iv) Display the details of all faculties whose salary is more than 60000 and have joined before the year 2007.
A) SELECT * FROM Faculty WHERE Salary>60000 AND YEAR(DoJ)<2007; OR
SELECT * FROM Faculty WHERE Salary>60000 AND DoJ<"2007-01-01";
(b) (ii) Display names of faculties after removing leading and trailing spaces.
A) SELECT TRIM(FacName) FROM Faculty;
(iii) Display total number of records in the table Faculty.
A) SELECT COUNT(*) FROM Faculty; OR
SELECT COUNT(FID) FROM Faculty;
29. Match the following SQL functions/clauses with their descriptions:
(A) P-2, Q-4, R-3, S-1 (B) P-2, Q-4, R-1, S-3
(C) P-4, Q-3, R-2, S-1 (D) P-4, Q-2, R-1, S-3
A) (B). P-2, Q-4, R-1, S-3
30. Consider the string: "Database Management System". Write suitable SQL queries for the following:
I. To extract and display "Manage" from the string.
II. Display the position of the first occurrence of "base" in the given string.
A) I. SELECT SUBSTRING('Database Management System', 10, 6);
II. SELECT INSTR('Database Management System', 'base');
31. Consider the following table:
ATHLETE, which stores AthleteID, Name, Country. The table displays basic information of the athletes
Table: ATHLETE
XII – IP(2025.26) 219 Unit 2 : MySQL
A) Write appropriate SQL queries for the following:
II. Display the names of all the Indian athletes in uppercase.
A) II. SELECT UPPER(Name) FROM ATHLETE WHERE COUNTRY = 'INDIA';
32.A) Rahul, who works as a database designer, has developed a database for a bookshop. This database
includes a table BOOK whose column (attribute) names are mentioned below:
BCODE: Shows the unique code for each book.
TITLE: Indicates the book’s title.
AUTHOR: Specifies the author’s name.
PRICE: Lists the cost of the book.
Table: BOOK
I. Write SQL query to display book titles in lowercase.
II. Write SQL query to display the highest price among the books.
III. Write SQL query to display the number of characters in each book title.
A) I. SELECT LOWER(TITLE) FROM BOOK;
II. SELECT MAX(PRICE) FROM BOOK;
III. SELECT LENGTH(TITLE) FROM BOOK;
33.B) Dr. Kavita has created a database for a hospital's pharmacy. The database includes a table named
MEDICINE whose column (attribute) names are mentioned below:
MID: Shows the unique code for each medicine.
MED_NAME: Specifies the medicine name
SUPP_CITY: Specifies the city where the supplier is located.
STOCK: Indicates the quantity of medicine available.
DEL_DATE: Specifies the date when the medicine was delivered.
Table: MEDICINE
Write the output of the following SQL Queries.
I. Select LENGTH(MED_NAME) from MEDICINE where STOCK > 100;
II. Select MED_NAME from MEDICINE where month(DEL_DATE) = 4;
IV. Select max(DEL_DATE) from MEDICINE;
A) i.
ii.
iv.
XII – IP(2025.26) 220 Unit 2 : MySQL
34) Write suitable SQL query for the following:
I. To display the average score from the test_results column (attribute) in the Exams table
II. To display the last three characters of the registration_number column (attribute) in the Vehicles table.
(Note: The registration numbers are stored in the format DL-01-AV-1234)
III. To display the data from the column (attribute) username in the Users table, after eliminating any leading
and trailing spaces.
IV. To display the maximum value in the salary column (attribute) of the Employees table.
V. To determine the count of rows in the Suppliers table.
A) I. SELECT AVG(test_results) FROM Exams;
II. SELECT RIGHT(registration_number, 3) FROM Vehicles;
III. SELECT TRIM(username) FROM Users;
IV. SELECT MAX(salary) FROM Employees;
V. SELECT COUNT(*) FROM Suppliers;
35) Write suitable SQL query for the following:
I. Round the value of pi (3.14159) to two decimal places.
II. Calculate the remainder when 125 is divided by 8.
III. Display the number of characters in the word 'NewDelhi'.
IV. Display the first 5 characters from the word 'Informatics Practices'.
V. Display details from 'email' column (attribute), in the 'Students' table, after removing any leading and
trailing spaces.
A) I. SELECT ROUND(3.14159, 2);
II. SELECT MOD(125, 8);
III. SELECT LENGTH('NewDelhi');
IV. SELECT LEFT('Informatics Practices', 5);
V. SELECT TRIM(email) FROM Students;
36. What will be the output of the following query ? SELECT MOD (5, 15);
(A) 10 (B) 3 (C) 0 (D) 5
37. Which of the following aggregate function returns the average of values in a specified column of a MySQL
table ?
(A) AVG(Column) (B) AVERAGE(Column) (C) MEAN(Column) (D) TOTAL(Column)
38. Now() in MySQL returns _______________.
(A) Today’s date (B) Today’s date and current time
(C) System’s date and time (D) Name of active database
39. What will be the output of the following query ? SELECT SUBSTR("Swachh Survekshan",2,4)
(A) wac (B) wach (C) shan (D) achh
40.What is the output of the following SQL Query ? SELECT INSTR("KNOWLEDGE","E");
(A) 7 (B) 5 (C) 6 (D) – 6
41. Consider the string 'PAINTING'. Write the SQL commands to display the following output :
(i) ING (ii) INT
A) (i) SELECT RIGHT('PAINTING',3); OR
SELECT SUBSTR('PAINTING',6,3); OR
SELECT SUBSTRING('PAINTING',6,3); OR
SELECT MID('PAINTING',6,3);
(ii) SELECT SUBSTR('PAINTING',3,3); OR
SELECT SUBSTRING('PAINTING',3,3); OR
SELECT MID('PAINTING',3,3);
Consider the table BIKES given below :
XII – IP(2025.26) 221 Unit 2 : MySQL
Table : BIKES
(b) Predict the output of the following queries based on the table BIKES given above :
(i) SELECT UCASE(TRIM(Brandname)) FROM BIKES WHERE Bid = 1003;
(ii) SELECT COUNT(Biketype) FROM BIKES;
A) (i) INDIANA
(ii) 9
42. Ms. Sridevi is a placement head in a reputed engineering institute and has created the following table to
store the records of students getting placement in various companies :
Table : Placement
Based on the given table, help Ms. Sridevi to write SQL queries for performing the following tasks :
(ii) To display the joining month name for Rising Star company.
Ms. Sridevi has written following queries. Write the output of each query :
A) SELECT MONTHNAME(DoJ) FROM Placement WHERE CompanyName = 'Rising Star';
(iii) SELECT LEFT (CompanyName, INSTR(CompanyName,"R")) FROM Placement where vacancies >=20;
A)
43. Consider the tables Faculty and Batch given below :
Table : Faculty
Table : Batch
Write SQL queries for the following :
(a) (ii) Display details of faculties who joined on Monday.
A) SELECT * FROM Faculty WHERE DAYNAME(DoJ)=’Monday’; OR
SELECT * FROM Faculty WHERE DAYOFWEEK(DoJ)=2;
XII – IP(2025.26) 222 Unit 2 : MySQL
(iv) Display the details of all faculties whose salary is more than 60000 and have joined before the year 2007.
A) SELECT * FROM Faculty WHERE Salary>60000 AND YEAR(DoJ)<2007; OR
SELECT * FROM Faculty WHERE Salary>60000 AND DoJ<"2007-01-01";
44. Consider the tables Faculty and Batch given below :
Table : Faculty
Table : Batch
(b) (ii) Display names of faculties after removing leading and trailing spaces.
A) SELECT TRIM(FacName) FROM Faculty;
(iii) Display total number of records in the table Faculty.
A) SELECT COUNT(*) FROM Faculty; OR
SELECT COUNT(FID) FROM Faculty;
45. What will be the output of the following query ? SELECT POWER(2,MOD(17,3));
(i) 8 (ii) 1 (iii) 0 (iv) 4
46. Which of the following is not an aggregate function in MYSQL ?
(i) AVG( ) (ii) MAX( ) (iii) LCASE( ) (iv) MIN( )
47. What will be the output of the following query ? SELECT SUBSTR("G20 2023 INDIA", 5, 4);
(i) G20 2 (ii) 2023 (iii) INDI (iv) 023
48. Which MySQL string function is used to extract a substring from a given string based on a specified
starting position and length ?
(i) SUBSTRING_INDEX() (ii) LENGTH( ) (iii) MID( ) (IV) TRIM( )
49. What will be the output of the following SQL queries :
(i) SELECT RIGHT ("CHANDRAYAN3",4);
(ii) SELECT ROUND(76345.456,2);
A) (i) YAN3
(ii) 76345.46
50) Consider the given table and write the following queries in MySQL :
Table: Sports
(i) To display Sid and name of those sports which are to be played in the month of September.
A) SELECT Sid, SName FROM Sports WHERE Monthname(DateofPlay)= "September"; OR
SELECT Sid, SName FROM Sports WHERE Month(DateofPlay)= 9; OR
SELECT Sid, SName FROM Sports WHERE Month(DateofPlay)= '9' OR
SELECT Sid, SName FROM Sports WHERE DateofPlay LIKE "%-09-%"; OR
SELECT Sid, SName FROM Sports WHERE DateofPlay>='2024-09-01' AND DateofPlay<='2024-09-30';
OR
SELECT Sid, SName FROM Sports WHERE DateofPlay BETWEEN '2024-09-01' AND '2024-09-30';
XII – IP(2025.26) 223 Unit 2 : MySQL
(ii) To display all Sports names in lower case.
A) SELECT LCASE(SName) FROM Sports; OR
SELECT LOWER(SName) FROM Sports;
(iii) To display last two characters of all sports names whose fees is less than 1500.
A) SELECT RIGHT(SName, 2) FROM Sports WHERE Fees<1500; OR
SELECT MID(SName,LENGTH(SName)-1,2) FROM Sports WHERE Fees<1500; OR
SELECT SUBSTR(SName,-2) FROM Sports WHERE Fees<1500; OR
SELECT SUBSTR(SName,LENGTH(SName)-1,2) FROM Sports WHERE Fees<1500; OR
SELECT SUBSTRING(SName,LENGTH(SName)-1,2) FROM Sports WHERE Fees<1500;
b) Predict the output of the following queries based on the table Sports given above :
(i) SELECT UCASE(TRIM(SName)) FROM Sports WHERE Sid=5 ;
A) BADMINTON
(ii) SELECT LEFT (SName,3) FROM Sports WHERE DateofPlay>"2024-09-13";
A) Law
Bad
(iii) SELECT SUBSTR (CoachId,1) FROM Sports WHERE SName="Cricket" or Fees>=2000;
A) S3
S4
51) Excellent Consultancy Pvt. Ltd. maintains two tables for all its employees.
Table: Employee
Write suitable SQL queries for the following task:
(i) Display the year of joining of all the employees from the table Employee.
A) SELECT YEAR(Joining_date) FROM Employee;
52. You have a table called "sales” that contains sales data for a retail store. Which SQL aggregate function
can be used to calculate the total number of rows or records in the "sales” table?
a. MAX() b. MIN() c. AVG() d. COUNT()
53. Which SQL function can be used to convert a text string to uppercase?
a. UCASE() b. LENGTH() c. MID() d. LTRIM()
54. You are working with a database that stores employee information. You need to retrieve the current date
and time. Which SQL function would you use for this purpose?
a. DATE() b. MONTH() c. DAY() d. NOW()
55. Predict the output of the following query: SELECT ROUND(15.789, 2);
a. 15.79 b. 15.789 c. 16 d. 15.8
56. Consider the given SQL QUERIES:
i. To retrieve the length of the given string "CBSE BOARD SQP 2023!", which SQL function should you
use?
a. LCASE() b. MID() c. LENGTH() d. TRIM()
ii. To find out if symbol is present in the values of email id column or not, which function out of the following
should be used?
a. Find( ) b. Instr( ) c. FindStr( ) d. OnStr( )
57. Consider the following records in “Cars” table and answer the given questions:
XII – IP(2025.26) 224 Unit 2 : MySQL
a. Write SQL query that will give the output as
Blu
Bla
Bro
Blu
Ans. SELECT LEFT(COLOR, 3) FROM Cars WHERE COLOR='Blue' OR COLOR='Black' OR
COLOR='Brown';
58. Attempt the following questions:
(i) Write a SQL query to calculate the remainder when 15 is divided by 4.
Ans. SELECT MOD(15, 4) AS Remainder;
(ii) Write a SQL query to retrieve the current year.
Ans. SELECT YEAR(NOW()) AS CurrentYear;
(iii) Write a SQL query to extract the first three characters from the string 'Hello,World!'.
Ans. SELECT LEFT('Hello, World!', 3) AS ExtractedString;
(iv)Write a SQL query to convert the text in the 'description' column of the 'product' table to uppercase.
Ans. SELECT UPPER(description) AS UppercaseDescription FROM product;
(v)Write a SQL query to display the position of'-' in values of ACC_NO column of table Bank.
Ans. SELECT INSTR(acc_no, '-') FROM bank;
59) Observe the given tables carefully and attempt the following questions:
Table : Bank
(iii) Write a SQL query to find the total amount of money across all branches.
Ans. SELECT SUM(AMOUNT) AS TOTAL_AMOUNT FROM BANK;
(v) Write a SQL query to find the minimum amount in a bank.
Ans. SELECT MIN(AMOUNT) from BANK;
60) Observe the given tables carefully and attempt the following questions:
Table : Customer
(iv) Write a SQL query to count the total records in CUSTOMER table.
Ans. SELECT COUNT(*) from CUSTOMER;
61. Predict the output of the following query: SELECT MOD (9,0);
i. 0 ii. NULL iii. NaN iv. 9
62. Which of the following SQL functions does not belong to the Math functions category?
i. POWER() ii. ROUND() iii. LENGTH() iv. MOD()
63. Predict the output of the following query: SELECT LCASE (MONTHNAME ('2023-03-05'));
i. May ii. March iii. may iv. march
64. In SQL, the equivalent of UCASE() is:
i. UPPERCASE () ii. CAPITALCASE() iii. UPPER() iv. TITLE ()
65. Consider the given SQL string: “12#All the Best!”
Write suitable SQL queries for the following:
i. Returns the position of the first occurrence of the substring “the” in the given string.
ii. To extract last five characters from the string.
XII – IP(2025.26) 225 Unit 2 : MySQL
A) i. SELECT INSTR("12#All the Best!","the");
ii. SELECT RIGHT("12#All the Best!",5);
66. What are aggregate functions in SQL? Name any two.
A. Aggregate functions are also called multiple row functions.
These functions work on a set of records as a whole, and return a single value for each column of the records
on which the function is applied.
Aggregate functions: MAX( ), MIN( ), AVG( ),SUM( ),COUNT( ),COUNT(*)
67. Based on the SQL table CAR_SALES,
Predict the output of the following queries based on the table CAR_SALES given above:
i. SELECT LEFT(SEGMENT,2) FROM CAR_SALES WHERE FUEL= "PETROL";
iii. SELECT SUM(QT1) "TOT SALE" FROM CAR_SALES WHERE FUEL= "DIESEL";
A)
68. Preeti manages database in a blockchain start-up. For business purposes, she created a table named
BLOCKCHAIN. Assist her by writing the following queries:
TABLE: BLOCKCHAIN
i. Write a query to display the year of oldest transaction.
ii. Write a query to display the month of most recent transaction.
iii. Write a query to display all the transactions done in the month of May.
iv. Write a query to count total number of transactions in the year 2022.
A) i. SELECT YEAR(MIN(TRANSACTION_DATE)) FROM BLOCKCHAIN;
ii. SELECT MONTH(MAX(TRANSACTION_DATE)) FROM BLOCKCHAIN;
iii. SELECT * FROM BLOCKCHAIN WHERE MONTHNAME (TRANSACTION_DATE)='MAY';
iv. SELECT COUNT(ID) FROM BLOCKCHAIN WHERE YEAR(TRANSACTION_DATE)=2022;
69. Write suitable SQL queries for the following:
i. To calculate the exponent for 3 raised to the power of 4.
ii. To display current date and time.
iii. To round off the value -34.4567 to 2 decimal place.
iv. To remove all the probable leading and trailing spaces from the column userid of the table named user.
v. To display the length of the string ‘FIFA World Cup’.
A) i. SELECT POWER(3,4);
ii. SELECT NOW();
iii. SELECT ROUND(-34.4567,2);
XII – IP(2025.26) 226 Unit 2 : MySQL
iv. SELECT TRIM(USERID) FROM USER;
v. SELECT LENGTH("FIFA World Cup");
70. Write the output of the following SQL query : SELECT LCASE(SUBSTR("Project Management",9,6));
(a) Manag (b) Manage (c) MANAGE (d) manage
71. Write the output of the following SQL command : select pow(2,2*2);
(a) 16 (b) 2 (c) 4 (d) 8
72. In SQL, returns the month name from the specified date.
(a) MONTH() (b) DATE() (c) MONTHNAME() (d) NOW()
73. Which of the following SQL function returns the number of values in the specified column ignoring the
NULL values ?
(a) COUNT(*) (b) COUNT(columnname) (c) LENGTH(*) (d) LENGTH(columnname)
74. Find the output of the following SQL queries : Select INSTR("Data Science","ie");
(a) 8 (b) -5 (c) True (d) False
75. Ananya, a database executive, needs to display a system’s current date and time. Suggest to her a suitable
SQL function name. Also write the query for the same.
A) NOW()
SELECT NOW();
76. Consider the table Customer given below and write SQL commands : TABLE : Customer
i) Display the details of all customers who have placed the order in the year 2023.
ii) Count the total number of customers from India.
iii) Display the last 9 characters of the email id of all customers of Denmark.
A) SELECT * FROM Customer WHERE YEAR(Orderdate)=2023; OR
SELECT * FROM Customer WHERE YEAR(Orderdate) IN (‘2023’); OR
SELECT * FROM Customer WHERE YEAR(Orderdate) IN (2023); OR
SELECT * FROM Customer WHERE YEAR(Orderdate) LIKE ‘2023’; OR
SELECT * FROM Customer WHERE YEAR(Orderdate) LIKE 2023;
ii) SELECT COUNT(*) FROM Customer WHERE Country= ‘India’; OR
SELECT COUNT(Country) FROM Customer WHERE Country =‘India’;
iii) SELECT RIGHT(Emailid,9) FROM Customer WHERE Country= ‘Denmark’; OR
SELECT RIGHT(Emailid,9) FROM Customer WHERE Country IN(‘Denmark’); OR
SELECT RIGHT(Emailid,9) FROM Customer WHERE Country LIKE ‘Denmark;
77. Write the output (i-iii) for the following SQL commands :
Table : CLUB
i) SELECT COUNT(*) FROM CLUB;
ii) SELECT SUM(Fee) FROM CLUB;
iii) SELECT LEFT(Activity,2) FROM CLUB WHERE Days='M,W';
A) i) 6
ii) 54000
iii) Sw
Da
XII – IP(2025.26) 227 Unit 2 : MySQL
OR
b)Find the output of the following SQL queries :
i) SELECT MID("Exam",1,2);
ii) SELECT MONTHNAME("2023-05-30");
iii) SELECT MONTH("2023-03-05");
A) i) Ex
ii) May
iii) 3
78) Write the SQL queries which will perform the following operations :
i) To display the day part from your date of admission, which is ‘2023-12-13’
ii) To convert your father’s email id ‘xyz@abc.com’ to uppercase.
iii) To count the number of characters in the string ‘India’
iv) To display today’s day name i.e., Sunday or Monday …
v) To display your height 5.41 after rounding off to 1 decimal place.
A) i) SELECT DAY(‘2023-12-13’);
ii) SELECT UCASE(‘xyz@abc.com’); OR
SELECT UPPER(‘xyz@abc.com’);
iii) SELECT LENGTH(‘India’);
iv) SELECT DAYNAME(NOW()); OR
SELECT DAYNAME(SYSDATE()); OR
SELECT DAYNAME(CURDATE());
v) SELECT ROUND(5.41,1);
b) Explain the following SQL functions using suitable examples :
i) LTRIM() ii) RTRIM() iii) INSTR( ) iv) MOD( ) v) TRIM( )
A) b.i) LTRIM() function is used to remove any leading spaces (whitespace characters) from a string.
Example: SELECT LTRIM(' HELLO') ;
Output: HELLO
ii) RTRIM() function is used to remove any trailing spaces (whitespace characters) from a string.
Example: SELECT RTRIM('HELLO ') ;
Output: HELLO
iii) The INSTR() function is used to find the starting position of a substring within a larger string.
Example: SELECT INSTR("SCIENCE","IE");
Output: 3
iv) MOD() function is used to calculate the remainder of a division operation between two numbers.
Example: SELECT MOD(10,4) ;
Output: 2
v) TRIM() function is used to remove leading and trailing spaces (whitespace characters) from a string.
Example: SELECT TRIM(' HELLO ') ;
Output: HELLO
79. Which of the following is the correct output of the following SQL command?
SELECT ROUND (7876.4568, 2);
(i) 7876.46 (ii) 7876.45 (iii) 7900 (iv) 7900.456
80. Aggregate functions are also known as:
(i) Scalar Functions (ii) Single Row Functions (iii) Multiple Row Functions (iv) Hybrid Functions
81. Ravisha has stored the records of all students of her class in a MYSQL table. Suggest a suitable SQL
clause that she should use to display the names of students in alphabetical order.
(i) SORT BY (ii) ALIGN BY (iii) GROUP BY (iv) ORDER BY
82. To remove the leading and trailing space from data values in a column of MySql Table, we use
(i) Left( ) (ii) Right( ) (iii) Trim( ) (iv) Ltrim( )
83. If the substring is not present in a string, the INSTR( ) returns:
(i) – 1 (ii) 1 (iii) NULL (iv) 0
84. Which of the following is not a valid aggregate function in MYSQL ?
(i) COUNT( ) (ii) SUM( ) (iii) MAX( ) (iv) LEN( )
85. Differentiate between COUNT( ) and COUNT(*) functions in MYSQL.
Give suitable examples to support your answer.
XII – IP(2025.26) 228 Unit 2 : MySQL
A)
COUNT(Column_Name) COUNT(*)
It returns the number of non-null values in the It returns the number of rows in the table
column used in COUNT()
Example:
SCode Sname Commission
S001 Amit 2500
S002 Jones
S003 Ahmed 2600
SELECT COUNT(Commission) FROM Sales;
will return 2
SELECT COUNT(*) FROM Sales;
will return 3
86. Consider the table Patient given below and write SQL commands. Table: Patient
(i) Display the details of all patients who were admitted in January
(ii) Count the total number of patients from Delhi.
(iii) Display the last 2 digits of the Patientid of all patients from Surgery Department.
A) (i) SELECT * FROM Patient WHERE MONTHNAME(Dateofadm)=”January”;
(ii) SELECT city, count(city) FROM Patient WHERE City=’Delhi’; OR
SELECT count(city) FROM Patient WHERE City=’Delhi’; OR
SELECT count(*) FROM Patient WHERE City=’Delhi’; OR
SELECT count(3) FROM Patient WHERE City=’Delhi’;
(iii) SELECT RIGHT(Patientid,2) FROM Patient; OR
SELECT SUBSTR(Patientid,length(Patientid)-1,2) FROM Patient;
87. Write the output (i-iii) for the following SQL commands.
Table: FASHION
(i) SELECT COUNT(Product) FROM FASHION;
(ii) SELECT SUM (Price*Qty) FROM FASHION WHERE Product="Night Cream";
(iii) SELECT LEFT (Product, 4) FROM FASHION WHERE Price>1500;
A) ) (i) 6
(ii) 34000
(iii) Foun
Nigh
88.Find the output of the following SQL queries :
(i) SELECT SUBSTR("CLIMATE CHANGE",4,4);
(ii) SELECT UCASE(RIGHT("Pollution",3));
XII – IP(2025.26) 229 Unit 2 : MySQL
(iii) SELECT LENGTH("HAPPY")+3;
A) (i) MATE
(ii) ION
(iii) 8
89. Write the SQL queries which will perform the following operations:
(i) To display the year from your Date of Admission which is '2023-05-15'.
(ii) To convert your email id 'ABC@XYZ.com' to lowercase.
(iii) To remove leading spaces from a string ‘ my country’.
(iv) To display current date.
(v) To display the value of 106
A) (i) SELECT YEAR(‘2023-05-15’); OR
SELECT YEAR(DOA) FROM XYZ;
(ii) SELECT LOWER(‘ABC@XYZ.com’); OR
SELECT LCASE(‘ABC@XYZ.com’);
(iii) SELECT LTRIM(‘ my country’); OR
SELECT TRIM(‘ my country’);
(iv) SELECT CURDATE(); OR
SELECT SYSDATE(); OR
SELECT CURRENT_DATE(); OR
SELECT CURRENT_TIMESTAMP() OR
SELECT NOW(); OR
SELECT DATE(NOW()); OR
SELECT LOCALTIME(); OR
SELECT LOCALTIMESTAMP();
(v) SELECT POWER(10,6); OR
SELECT POW(10,6)
OR
Consider a table PRODUCT with the following data:
Table: PRODUCT
Write SQL queries using SQL functions to perform the following operations :
(i) Display the first 3 characters of all Itemnames.
(ii) Display the names of all items whose Stockday is "Monday"
(iii) Display the total price of all the products.
(iv) Display the maximum Price.
(v) Display the average Price of all the products by the company named 'Logitech'
A)
(i) SELECT LEFT(ITEMNAME,3) FROM PRODUCT; OR
SELECT MID(ITEMNAME,1,3) FROM PRODUCT; OR
SELECT SUBSTR(ITEMNAME,1,3) FROM PRODUCT; OR
SELECT SUBSTRING(ITEMNAME,1,3) FROM PRODUCT;
(ii) SELECT ITEMNAME FROM PRODUCT WHERE DAYNAME(STOCKDATE)='MONDAY'; OR
SELECT ITEMNAME FROM PRODUCT WHERE DAYOFWEEK(STOCKDATE)=2;
(iii) SELECT SUM(PRICE) FROM PRODUCT;
(iv) SELECT MAX(PRICE) FROM PRODUCT;
(v) SELECT AVG(PRICE) FROM PRODUCT WHERE COMPANY='Logitech';
90. If column “Fees” contains the data set (5000,8000,7500,5000,8000), what will be the output after the
execution of the given query? SELECT SUM (DISTINCT Fees) FROM student;
i. 20500 ii. 10000 iii. 20000 iv. 33500
XII – IP(2025.26) 230 Unit 2 : MySQL
91. Which SQL statement do we use to find out the total number of records present in the table ORDERS?
i. SELECT * FROM ORDERS; ii. SELECT COUNT (*) FROM ORDERS;
iii. SELECT FIND (*) FROM ORDERS; iv. SELECT SUM () FROM ORDERS;
92. Which one of the following is not an aggregate function?
i. ROUND() ii. SUM() iii. COUNT() iv. AVG()
93. Which one of the following functions is used to find the largest value from the given data in MySQL?
i. MAX( ) ii. MAXIMUM( ) iii. BIG( ) iv. LARGE( )
94. In SQL, which function is used to display current date and time?
i. Date () ii. Time () iii. Current () iv. Now ()
95. Write outputs for SQL queries (i) to (iii) which are based on the given table PURCHASE:
i. SELECT LENGTH(CNAME) FROM PURCHASE WHERE QUANTITY>100;
ii. SELECT CNAME FROM PURCHASE WHERE MONTH(DOP)=3;
iii. SELECT MOD (QUANTITY, DAY(DOP)) FROM PURCHASE WHERE CITY=‘CHANDIGARH’;
A) i. 8
ii. No Output
iii. 0
15
96. Write suitable SQL query for the following:
i. Display 7 characters extracted from 7th left character onwards from the string ‘INDIA SHINING’.
ii. Display the position of occurrence of string ‘COME’ in the string ‘WELCOME WORLD’.
iii. Round off the value 23.78 to one decimal place.
iv. Display the remainder of 100 divided by 9.
v. Remove all the expected leading and trailing spaces from a column userid of the table ‘USERS’.
A) i. select mid('INDIA SHINING',7,7);
ii. select INSTR('WELCOME WORLD','COME');
iii. select round(23.78,1);
iv. select mod(100,9);
v. select trim(userid) from users;
97. Explain the following SQL functions using suitable examples.
i. UCASE( ) ii. TRIM( ) iii. MID( ) iv. DAYNAME( ) v. POWER( )
A) 1. UCASE(): It converts the string into upper case.
Example: SELECT UCASE(‘welcome world’);
Output: WELCOME WORLD
2. TRIM(): It removes the leading and trailing
spaces from the given string.
Example: SELECT TRIM(‘ Welcome world ‘ );
Output: Welcome world
3. MID(): It extracts the specified number of
characters from given string.
Example: SELECT MID(‘ Welcome world,4,,4);
Output: Come
4. DAYNAME(): It returns the weekday name for
a given date
Example: SELECT DAYNAME(‘2022-07-22’);
Output: Friday
5. POWER(): It returns the value of a number
raised to the power of another number.
Example: SELECT POW(6,2);
XII – IP(2025.26) 231 Unit 2 : MySQL
Output: 36
98. Shreya, a database administrator has designed a database for a clothing shop. Help her by writing answers
of the following questions based on the given table:
TABLE: CLOTH
i. Write a query to display cloth names in lower case.
ii. Write a query to display the lowest price of the cloths.
A) i. SELECT LOWER(CNAME) FROM CLOTH;
ii. SELECT MIN(PRICE) FROM CLOTH;
99. Find the output of the following SQL queries:
(i) SELECT ROUND(21.341, 2);
(ii) SELECT MOD(10, 3);
A) (i) 21.34
(ii) 1
100. Give any two differences between MOD() and AVG() functions in SQL.
A) MOD() :
i. It is a math/numeric single row function.
ii. MOD(A,B) returns the remainder after dividing number A by number B.
iii. For Example: SELECT MOD(5,3); will give 2 as output
AVG() :
i. It is an aggregate function
ii. AVG(column) returns the average of the values for the specified column.
iii. For Example : SELECT AVG(QTY) FROM PRODUCT; will give the output 6.0000 if the
QTY column has the values 6,8 and 4
101. Find the output of the following SQL queries :
(i) SELECT MID("YOUNG INDIA",5);
(ii) SELECT INSTR("MACHINE INTELLIGENCE","IN");
A) (i) G INDIA (ii) 5
102. Ms. Anubha is working in a school and stores the details of all students in a Table: SCHOOL
Table : SCHOOL
Write the SQL statements from the given table to:
(i) Remove TRAILING SPACES from column Sname.
(ii) Display the names of students who were born on Tuesday.
A) (i) SELECT RTRIM(Sname) FROM SCHOOL;
(ii) SELECT Sname FROM SCHOOL WHERE DAYOFWEEK(Dob) = 3;
103. Predict the output of the following SQL queries from the above Table: SCHOOL
(i) SELECT AVG(Per) FROM SCHOOL WHERE House="Red";
XII – IP(2025.26) 232 Unit 2 : MySQL
(ii) SELECT Sname, Per FROM SCHOOL WHERE MONTH(Dob)=11;
A) (i) 70.0000
(ii) Swapnil Pant 84
104.Predict the output of the following SQL queries:
(i) SELECT LENGTH("GOOD LUCK");
(ii) SELECT POWER(3, 3);
(iii) SELECT UPPER("examination");
A) (i) 9
(ii) 27
(iii) EXAMINATION
105. Consider a Table "PETDATA" with the following data :
Table : PETDATA
Write SQL queries for the following :
(i) Display all the pet names in uppercase.
(ii) Display the total price of all the pets.
(iii) Display the average discount available on all the pets.
A) (i) SELECT UPPER(Pname) FROM PETDATA;
(ii) SELECT SUM(Price) FROM PETDATA;
(iii) SELECT AVG(Discount) FROM PETDATA;
106.Write the names of SQL functions to perform the following operations :
(a) Display the name of the month from the given date value.
(b) Display the day of month from the given date value.
(c) Count the number of characters in a given string.
A) (a) MONTHNAME()
(b) DAYOFMONTH()
(c) LENGTH()
107. Consider the following Table : ITEM
Find the output of the following SQL query : SELECT LEFT(INAME,3) FROM ITEM;
A) (c) Ske
Rol
Gel
Not
108. Consider the Table FURNITURE with the following data : Table : FURNITURE
XII – IP(2025.26) 233 Unit 2 : MySQL
Write SQL queries for the following :
(i) Display the highest Price.
(ii) Display the Item with their price rounded to 1 decimal place.
A) (i) SELECT MAX(PRICE) FROM FURNITURE;
(ii) SELECT MAX(PRICE) FROM FURNITURE;
109. Consider the following table :
Table : EMPLOYEE
Predict the output for the following SQL queries:
(i) SELECT MAX(Salary), FROM EMPLOYEE;
(ii) SELECT COUNT(Dept) FROM EMPLOYEE;
(iii) SELECT UCASE(Ename) FROM EMPLOYEE WHERE MONTH(Doj)=2;
(iv) SELECT Ename FROM EMPLOYEE WHERE Right(Ecode,1)=5;
A) (i) 28000 OR Error in command (due to comma after MAX() function)
(ii) 5 (iii) SUNIL (iv) Ankit
RISHU
110. Table : EMPLOYEE
Based on the given table EMPLOYEE write SQL queries to perform the following operations:
(i) Count the total number of employees.
(ii) Display the minimum salary from each area.
(iii) Display the average salary from each department where number of employees is more than 1.
(iv) Display all the records in descending order of date of joining.
A) (i) SELECT COUNT(*) FROM EMPLOYEE;
(ii) SELECT MIN(Salary), Area FROM EMPLOYEE GROUP BY Area;
(iii) SELECT AVG(Salary), Dept FROM EMPLOYEE GROUP BY Dept HAVING COUNT(*)>1;
(iv) SELECT * FROM EMPLOYEE ORDER BY Doj DESC;
111.Find the output of the following SQL Queries:
(i) SELECT ROUND(7658.345,2)
(ii) SELECT MOD(ROUND(13.9,0),3)
XII – IP(2025.26) 234 Unit 2 : MySQL
A) (i) ROUND(7658.345,2)
(ii) MOD(ROUND(13.9,0),3
7658.35
112. Give any two differences between the POWER() and SUM( ) SQL functions.
POWER( ) SUM( )
Returns single result for each row when applied Returns single result by grouping all rows of table
to a table when applied
It is single row function It is multiple row function or aggregate function
It takes two arguments It takes only one argument
Syntax: Syntax:
SELECT POWER(M,N) SELECT SUM(column name) FROM table name
Ex: SELECT POWER(3,2); Ex: SELECT SUM(Salary) FROM Emp;
113. Find the output of the following SQL queries:
a) SELECT SUBSTR(“FIT INDIA MOVEMENT”,5);
b) SELECT INSTR(“ARTIFICIAL INTELLIGENCE”,”IA”);
A)
a)SUBSTR(“FIT INDIA MOVEMENT”,5)
INDIA MOVEMENT
b)INSTR(“ARTIFICIAL INTELLIGENCE”,”IA”)
8
114. Ms Mohini is working in a school and stores the details of all student in a table SCHOOLDATA.
Table : SCHOOLDATA
Admno Name Class House Percent Gender Dob
20150001 Aditya Das 10 Green 86 Male 2006-02-20
20140212 Harsh Sharma 11 Red 75 Male 2004-10-05
20090234 Swapnil Pant 10 Yellow 84 Female 2005-11-21
20130216 Soumen Rao 9 Red 91 Male 2006-04-10
20190227 Rahil Arora 10 Blue 70 Male 2005-05-14
20120200 Akasha Singh 11 Red 64 Female 2004-12-16
Write SQL statements from the above given table to
(i) to remove leading spaces from the column Name
(ii) Display the names of students who were born on Sunday
A) (i) SELECT LTRIM(Name) FROM SCHOOLDATA; OR
SELECT TRIM(Name) FROM SCHOOLDATA
(ii) SELECT NAME FROM SCHOOLDATA WHERE DAYNAME(DOB)=’SUNDAY’;
115. Predict the output of the following SQL queries from the given table SCHOOLDATA
(i) SELECT MAX(percent) FROM SCHOOLDATA;
(ii) SELECT LEFT(Gender,1), Name FROM SCHOOLDATA WHERE YEAR(DOB)=2005;
A) (i) MAX(percent)
91
(ii) LEFT(Gender,1) Name
F Swpanil Pant
M Rahil Arora
116. Predict the output of the following SQL queries:
(i) SELECT TRIM(“ ALL THE BEST “);
(ii) SELECT POWER(5,2);
(iii) SELECT UPPER(MID(“start up india”,10));
A) (i) A)TRIM(“ ALL THE BEST “)
ALL THE BEST
(ii) POWER(5,2)
25
XII – IP(2025.26) 235 Unit 2 : MySQL
(iii) UPPER(MID(“start up india”,10))
INDIA
117. Consider a table “MYPET” with the following data:
Table : MYPET
Pet_ Pet_Name Breed LifeSpan Price Discount
id
101 Rocky Labrador Retriever 12 16000 5
202 Duke German Shepherd 13 22000 10
303 Oliver Bulldog 10 18000 7
404 Cooper Yorkshire Terrier 16 20000 12
505 Oscar Shih Tzu NULL 25000 8
Write SQL queries for the following:
(i) Display the Breed of all the pets in uppercase.
(ii) Display the total price of all the pets.
(iii) Display the average life span of all the pets.
A) (i) SELECT UPPER(Breed) FROM MYPET;
SELECT UCASE(Breed) FROM MYPET;
(ii) SELECT SUM(Price) FROM MYPET;
(iii) SELECT AVG(LifeSpan) FROM MYPET;
118.Write the names of SQL functions to perform the following operations:
(i) Display name of the Month from your date of birth.
(ii) Convert email-id to lowercase.
(iii) Count the number of characters in your name.
A) (i) MONTHNAME( )
(ii) LOWER( ) or LCASE( )
(iii) LENGTH( )
119. Consider the following table: PRODUCT
Table : PRODUCT
PID PNAME PRICE QUANTITY
P1001 Eraser 10.50 5
P1002 Ball Pen 15.00 2
P1003 Gel Pen 25.10 3
P1004 Ruler 5.0 1
Find the output of the following SQL queries:
(i) SELECT 10+MOD(QUANTITY,3) FROM PRODUCT WHERE PNAME=”Eraser”;
(ii) SELECT ROUND(PRICE,2)*QUANTITY FROM PRODUCT WHERE QUANTITY>2;
(iii) SELECT UCASE(RIGHT(PNAME,2)) FROM PRODUCT;
A) (i)10+MOD(QUANTITY,3)
12
(ii) ROUND(PRICE,2)*QUANTITY
52.50
75.30
(iii)UCASE(RIGHT(PNAME,2))
ER
EN
EN
ER
120. Consider the table : ITEM
XII – IP(2025.26) 236 Unit 2 : MySQL
Write SQL series for the following:
(i) Display all the records in descending order of Stockdate.
(ii) Display the type and total number of items of each type.
(iii) Display the least price
(iv) Display the Itemname with their price rounded to decimal place.
A) (i) SELECT * FROM ITEM ORDER BY Stockdate DESC;
(ii) SELECT Type, COUNT(*) FROM ITEM GROUP BY Type;
(iii) SELECT MIN(Price) FROM ITEM;
(iv) SELECT Itemname, ROUND(Price,1) FROM ITEM;
121. Consider the following table:
Predict the output for the following SQL Queries:
(i) SELECT MAX(Qtysold), MIN(Qtysold) FROM SALESMAN;
(ii) SELECT COUNT(Area) FROM SALESMAN;
(iii) SELECT LENGTH(Sname) FROM SALESMAN WHERE MONTH(Dateofjoin)=10;
(iv) SELECT Sname FROM SALESMAN WHERE RIGHT(Scode,1)=5;
A) (i)MAX(Qtysold) MIN(QTysold)
280 68
(ii)COUNT(Area)
5
(iii)LENGTH(Sname)
4
5
(iv) Sname
Ankit
Based on the given table SALESMAN write SQL queries to perform the following operations:
(i) Count the total number of salesman.
(ii) Display all the records in ascending order of area.
A) (i) SELECT COUNT(*) FROM SALESMAN;
(ii) SELECT * FROM SALESMAN ORDER BY AREA ASC;
122. Predict the output of the following queries:
i. Select power(5,3); ii. Select mod(5,3);
A) i. 125
ii. 2
XII – IP(2025.26) 237 Unit 2 : MySQL
123.Briefly explain the purpose of the following SQL functions: i. power() ii. mod()
A) i. power(): It returns the value of a number raised to the power of another number.
For example: Select power(5,3);
Output: 125
ii. mod(): It returns the remainder of a number divided by another number.
For example: Select mod(5,3);
Output: 2
124. Help Reshma in predicting the output of the following queries:
i) select round(8.72,3); ii) select round(9.8);
A) Output: i) 8.720 ii) 10
125. Mr. Som, a HR Manager in a multinational company “Star-X world” has created the following table to
store the records of employees:
Table: Emp
He has written following queries:
i) select max(year(DOB)) from emp;
ii) select ENAME from emp where month(DOJ)=11;
Predict the output.
A) Output: i) 2001 ii) Melinda
126. Based on the table given above, help Mr. Som writing queries for the following task:
i) To display the name of eldest employee and his/her date of birth.
ii) To display the name of those employees whose joining month is May.
A) i) selectENAME,min(year(DOB)) from emp;
ii) select ENAME from emp where month(DOJ)=5;
127. Predict the output of the following queries:
i. select instr('exams@cbse.nic.in','.');
ii. selectsubstr('exams@cbse.nic.in',7,4);
iii. select left('exams@cbse.nic.in',5);
A) Output: i. 11 ii. cbse iii. exams
128. Ms.Saumya is working on a MySQL table named ‘Hotel’ having following structure:
She need to perform following task on the table:
i. To fetch last 2 characters from the user_id column.
ii. To display the values of name column in lower case.
iii. To display 3 characters from 3rd place from the column city.
Suggest suitable SQL function for the same. Also write the query to achieve the desired task.
A) i. right()
select right(user_id,2) from hotel;
ii. lower()
select lower(name) from hotel;
iii. mid()/substr()/substring()
SELECT MID(CITY,3,3) FROM HOTEL;
XII – IP(2025.26) 238 Unit 2 : MySQL
129. Reena is working with functions of MySQL. Explain her following: (
i. What is the purpose of now () function?
ii. How many parameters does it accept?
iii. What is the general format of its return type?
A) i. It returns the current date and time.
ii. None
iii. The return type for NOW() function is either in ‘YYYY-MM-DD HH:MM:SS’ format or
YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric
context.
130. While dealing with string data type in MySQL, its observed that sometimes unnecessary space character
comes in between which hampers the successful execution of a string manipulation module. Name the suitable
MySQL function (s) to remove leading, trailing and both type of space characters from a string. Also
give MySQL queries to depict the same.
A) i. To remove leading space characters: ltrim()
ii. To remove trailing space characters: rtrim()
iii. To remove both type of space characters: trim()
MySQL Queries: Select ltrim(‘ Hello ’);
Select rtrim(‘ Hello ’);
Select trim(‘ Hello ’);
Output: Hello
131. Carefully observe the following table named‘stock’:
Table: stock
Write SQL query for the following:
To display the records in decreasing order of price.
A) select * from stock order by price desc;
132. Satyam, a database analyst has created the following table:
Table: Student
He has written following queries:
(a) select sum(MARKS) from student where OPTIONAL= ‘IP’ and STREAM= ‘Commerce’;
(b) select max(MARKS)+min(MARKS) from student where OPTIONAL= ‘CS’;
(c) selectavg(MARKS) from student where OPTIONAL= ‘IP’;
(d) select length(SNAME) from student where MARKS is NULL;
Help him in predicting the output of the above given queries.
A) Output: (a) 193 (b) 194 (c) 93.75 (d) 6
133. Based on the above given table named ‘Student’, Satyam has executed following queries:
Select count(*) from student;
Select count(MARKS) from student;
Predict the output of the above given queries.
Also give proper justifications of the output generated through each query.
A) First query will produce the output 7.
XII – IP(2025.26) 239 Unit 2 : MySQL
Justification: count (*) will count and display total number of rows (irrespective of any null value present in
any of the column).
Second query will produce the output 6.
Justification: count (col_name) will count and display total number of not null values in the specified column.
134.Write the output of the following SQL command : select round(3456.885, 2);
(A) 3456.88 (B) 3456.89 (C) 3400 (D) 3500
135. An aggregate function performs a calculation on _________ and returns a single value.
(A) single value (B) multiple values (C) no value (D) None of the above
136. Which one of the following would arrange the rows in ascending order in SQL ?
(A) SORT BY (B) ALIGN BY (C) GROUP BY (D) ORDER BY
137. The SQL string function that returns the index of the first occurrence of substring is __________ .
A) INSTR
138. Discuss the purpose of count(*) function with the help of a suitable example.
A) COUNT(*) is used to return cardinality of selected rows from a table.
Example: SELECT COUNT(*) FROM HOTEL ;
139. Find the output of the following SQL queries :
(i) SELECT SUBSTR("Innovation",3,4) ;
(ii) SELECT RIGHT("Innovation",5) ;
A) a) (i) nova (ii) ation
140. Find the output of the following SQL queries :
(i) SELECT INSTR("COVID-19","V") ;
(ii) SELECT MOD(5,2) ;
A) (i) 3 (ii) 1
140. Consider the following table School :
Table : School
Write SQL query for the following :
Display the minimum Percentage secured by the students of Class 10.
A) SELECT MIN(Percentage) FROM School WHERE Class=10 ;
141. Write the SQL functions which will perform the following operations :
(i) To display the name of the weekday for your date of birth
(ii) To convert e-mail-id to lowercase
(iii) To count the number of characters in your name
(iv) To display the first character of your name
(v) To calculate the average marks secured by the class
A) (i) DAYNAME()
(ii) LCASE() OR LOWER()
(iii) LENGTH()
(iv) LEFT() OR SUBSTR() OR MID() OR SUBSTRING()
(v) AVG()
142. Consider a table ITEM with the following data :
XII – IP(2025.26) 240 Unit 2 : MySQL
Write SQL queries using SQL functions to perform the following operations :
(i) Display the first 3 characters of the Itemname.
(ii) Display the month name from the Stockdate.
(iii) Display the total price of the whole stock.
(iv) Display the average Price of all the stocks.
(v) Display all the Price round off up to 2 decimal places.
A))(i) SELECT LEFT(Itemname,3) FROM ITEM; OR
SELECT MID(Itemname,1,3) FROM ITEM ; OR
SELECT SUBSTR(Itemname,1,3) FROM ITEM OR
SELECT SUBSTRING(Itemname,1,3) FROM ITEM ;
(ii) SELECT MONTHNAME(Stockdate) FROM ITEM ;
(iii) SELECT SUM(Price) FROM ITEM ;
(iv) SELECT AVG(Price) FROM ITEM ;
(v) SELECT ROUND(Price,2) FROM ITEM ;
143. Write the output of the following SQL command. select round(49.88);
a. 49.88 b. 49.8 c. 49.0 d. 50
144. The avg( ) function in MySql is an example of ___________
a. Math function b. Text function c. Date Function d. Aggregate Function
145. Write the SQL command that will display the current time and date
A) Select now();
146.Consider the table STUDENT given below:
Help Ritesh to write the command to display the name of the youngest student?
a. select name,min(DOB) from student ;
b. select name,max(DOB) from student ;
c. select name,min(DOB) from student group by name ;
d. select name,maximum(DOB) from student;
A) b. select name,max(DOB) from student ;
147. State any two differences between single row functions and multiple row functions.
A) Differences between single row functions and multiple row functions.
(i) Single row functions work on one row only whereas multiple row functions group rows
(ii) Single row functions return one output per row whereas multiple row functions return only one output for
a specified group of rows.
148. Consider the decimal number x with value 8459.2654. Write commands in SQL to:
XII – IP(2025.26) 241 Unit 2 : MySQL
i. round it off to a whole number
ii. round it to 2 places before the decimal.
A) i. select round(8459.2654);
ii. select round(8459.2654,-2);
149. Anjali writes the following commands with respect to a table employee having fields, empno, name,
department, commission.
Command1: Select count(*) from employee;
Command2: Select count(commission) from employee;
She gets the output as 4 for the first command but gets an output 3 for the second command.
Explain the output with justification.
A) This is because the column commission contains a NULL value and the aggregate functions do not take
into account NULL values. Thus Command1 returns the total number of records in the table whereas
Command2 returns the total number of non NULL values in the column commission.
150) Consider the following SQL string: “Preoccupied”
Write commands to display: a. “occupied” b. “cup”
A) a. select substr("Preoccupied", 4); (OR)
select substring("Preoccupied", 4); (OR)
select mid("Preoccupied",4); (OR)
select right(("Preoccupied"”, 8);
b. select substr("Preoccupied" ,6,3); (OR)
select substring("Preoccupied", 6,3); (OR)
select mid(("Preoccupied" ,6,3);
151. Considering the same string “Preoccupied”
Write SQL commands to display:
a. the position of the substring ‘cup’ in the string “Preoccupied”
b. the first 4 letters of the string
A) a. select instr 'Preoccupied' , ‘ 'cup'));
b. select left 'Preoccupied',4);
152. Write the SQL functions which will perform the following operations:
i) To display the name of the month of the current date.
ii) To remove spaces from the beginning and end of a string, “ Panorama “.
iii) To display the name of the day eg, Friday or Sunday from your date of birth, dob.
iv) To display the starting position of your first name(fname) from your whole name (name).
v) To compute the remainder of division between two numbers, n1 and n2
A) i) monthname(date(now()))
ii) trim(“ Panaroma “)
iii) dayname(date(dob))
iv) instr(name, fname)
v) mod(n1,n2)
153. Consider a table SALESMAN with the following data:
Write SQL queries using SQL functions to perform the following operations:
a) Display salesman name and bonus after rounding off to zero decimal places.
b) Display the position of occurrence of the string “ta” in salesman names.
c) Display the four characters from salesman name starting from second character.
d) Display the month name for the date of join of salesman
e) Display the name of the weekday for the date of join of salesman
A) i) Select sname, round(bonus,0) from Salesman;
XII – IP(2025.26) 242 Unit 2 : MySQL
ii) Select instr(Sname, “ta”) from Salesman;
iii) Select mid(Sname,2,4) from Salesman; OR
Select Substring(Sname,2,4) from Salesman;
iv) Select monthname(DateofJoin) from Salesman;
v) Select dayname(DateofJoin) from Salesman;
154. Which of the following are correct aggregate functions in SQL:
(i) AVERAGE() (ii) MAX() (iii) COUNT() (iv) TOTAL()
155. On the basis of following table answer the given questions:
Table: CUSTOMER_DETAILS
(ii) What will be the output of the following query: Select max(DOJ) From Customer_Details;
A)
+------------+
| max(DOJ) |
+------------+
| 1998-02-21 |
+------------+
156. Write commands in SQL for (i) to (iii) and output for (iv) and (v).
Table : Store
(i) SELECT MIN(DATEOPEN) FROM STORE;
A) Min(DateOpen)
2015-02-06
157. Consider the table FANS and answer the following.
Table: FANS
i. To display the dob of the youngest fan.
A. SELECT MAX(FAN_DOB) FROM FANS;
158. Table student has the columns RNO and SCORE. It has 3 rows in it. Following two SQL statements
were entered that produced the output (AVG(SCORE) as 45 and COUNT(SCORE) as 2):
(i) AVG(SCORE) (ii)COUNT(SCORE )
Data in SCORE column is same in two rows. What data is present in the SCORE column in the three rows ?
A) 45
45
NULL
XII – IP(2025.26) 243 Unit 2 : MySQL
159. Consider the following table ‘Transporter’ that stores the order details about items to be transported.
Write SQL commands for the statements (i) to (viii) and write output for SQL queries (ix) and (x)
Table : TRANSPORTER
(i) SELECT MAX(TRAVELDATE) FROM TRANSPORTER WHERE DRIVERGRADE=’A’;
A) MAX(TRAVELDATE)
2019-04-19
160. Consider the following table:
Table: Results
Write the Outputs that the following SQL statements will generate:
(i) SELECT AVG(SCORE) FROM RESULTS WHERE EXAMID = 1;
A) 24
161. Consider the following table ‘Activity’. Write SQL commands for the statements (i) to(viii) and write
output for SQL queries (ix) and (x).
Table : Activity
(i) To display HOUSE wise, Lowest points scored.(ie. Display house and lowest points
scored for each house)
A) SELECT HOUSE, MIN(POINTS) FROM Activity GROUP BY HOUSE;
(ii) SELECT AVERAGE(POINTS) FROM Activity WHERE HOUSE = ' Gandhi ' or HOUSE = ' Bose ' ;
A) AVERAGE(POINTS)
250
XII – IP(2025.26) 244 Unit 2 : MySQL
CBSE – QUESTION BANK QUESTIONS
Q1.A School in Delhi uses database management system to store student details. The school maintains a
database 'school_record' under which there are two tables.
Student Table : Maintains general details about every student enrolled in school.
StuLibrary Table : To store details of issued books. BookID is the unique identification number issued to
each book. Minimum issue duration of a book is one Day.
i. Identify the SQL Query which displays the data of StuLibrary table in ascending order of
Student-ID.
i) Select * from StuLibrary Order By BookID
ii) Select * from StuLibrary Order By StuID
iii) Select * from StuLibrary Order By StuID ASC
iv) Select * from StuLibrary Order By StuID DESC
Choose the correct option:
a. Both Query i) and iv) will display the desired data.
b. Both Query i) and ii) will display the desired data.
c. Both Query iii) and iv) will display the desired data.
d. Both Query ii) and iii) will display the desired data.
ii. The Primary Key for StuLibrary Table is/are …….
a. BookID b. BookID,StuID
c. BookID,Issued_date d.Issued_date
iii. Which of the following SQL Query will fetch ID of those issued books which have not been returned?
a. SELECT BookID from StuLibrary where BookID is NULL;
b. SELECT BookID from StuLibrary where StuID is NULL;
c. SELECT BookID from StuLibrary where Issued_date is NULL;
d. SELECT BookID from StuLibrary where Return_date is NULL;
iv. The Alternate Key for Student Table will be ……….
a. StuName b. StuContact
c. StuAadhar d. StuClass
v. Which of the following SQL Query will display dates on which number of issued books is greater than 5?
a. SELECT Issued_date from StuLibrary GROUP BY Issued_date where COUNT(*)>5;
b. SELECT Issued_date from StuLibrary GROUP BY Return_date having count(*)>5
c. SELECT Issued_date from StuLibrary GROUP BY Issued_date having count(*)>5
d. SELECT Issued_date from StuLibrary GROUP BY Return_date where COUNT(*)>5
Q.2. Tejasvi Sethi, a car dealer has stored the details of all cars in her showroom in a table called
CARMARKET. The table CARMARKET has attributes CARCODE which is a primary key, CARNAME,
COMPANY, COLOR, COST (in lakh rupees) of the car and DOM which is the Date of Manufacture of the
car.
Answer any four questions based on the table CARMARKET from the below mentioned questions.
XII – IP(2025.26) 245 Unit 2 : MySQL
Table: CARMARKET
Choose the correct SQL query to do the following (for parts 1 to 4)
i. Display the carname along with the charges rounded off to 1 digit after decimal place.
a. Select carname,round(cost) from carmarket;
b. Select carname,round.cost(1) from carmarket;
c. Select carname,round.cost() from carmarket;
d. Select carname, round(cost,1) from carmarket;
CORRECT ANSWER – d
ii. Display the carname, color and position of the character ‘E’ in the color of all the cars.
a. select carname,color from carmarket where color like “%E%”;
b. select carname,color,instr(color,'E') from carmarket;
c. select carname,color from carmarket where color = “%E%”;
d. select carname,color,substr(color,1,’E’) from carmarket;
iii. Display the carname ,name of the company in lower case of all cars whose year (of dom) is 2020.
a. select carname,lcase(company) from carmarket where year(dom) = 2020;
b. select carname,lcase(company) from carmarket where yearof(dom) like '2020%';
c. select carname,lower(company) from carmarket where dom from '2020-01-01' to '2020-12-31';
d. select carname,lower(company) from carmarket where yearfrom(dom) = 2020;
iv. Display the number of cars manufactured each year.
a. select count(*),year(dom) from carmarket where year(dom) = distinct;
b. select count(*),year(dom) from carmarket group by year(dom);
c. select count(carmarket),year(dom) from carmarket group by year(dom);
d. select count(distinct *),year(dom) from carmarket group by year(dom);
v. What is the cardinality and degree of the table CARMARKET?
a. Cardinality = 8 and Degree = 6
b. Cardinality = 6 and Degree = 7
c. Cardinality = 7 and Degree = 6
d. Cardinality = 7 and Degree = 8
Q.3. A Departmental store ‘Iconic’ is planning to automate its system so that they can store all the records on
computer. They contacted a Software Company to make the software for the same. The company suggested
that there is need of a front end and back-end software. The major challenge was to keep the record of all the
items available in the store. To overcome the problem, the software company has shown the glimpses of the
database and table required to resolve their problem:
Database Name: Iconic
Table Name: Garment
Attributes of the table: Gcode – Numeric, Gname – Character 25, Size - Character 5, Colour – Character 10,
Price – Numeric
Consider the following records in ‘Garment’ table and answer the given questions:
XII – IP(2025.26) 246 Unit 2 : MySQL
i. Choose the command that will give the output as:
a. Select left(COLOUR,3) from GARMENT where COLOUR like “B%”;
b. Select COLOUR from GARMENT where COLOUR not like “%B%”;
c. Select mid(COLOUR,3) from GARMENT where COLOUR like “B%”;
d. Select COLOUR from GARMENT where COLOUR = ‘B%’;
Answer: a
ii. Choose the correct command for the following purpose. To delete the record with GCode as 116
a. Delete * from GARMENT where GCode=’116’; b. Delete from GARMENTS where GCode =116; c.
Delete from GARMENT where GCode =116;
d. Delete from GARMENT where GCode is ’116’;
Answer: b
iii. Give the output of : Select GName, Price from GARMENT order by Price Desc;
Answer: c
iv. Choose the correct command for the following purpose.
To change the colour of GARMENT with code as 116 to “Orange”.
a. Update GARMENTS set COLOUR=”Orange” where Gcode=116;
b. Update GARMENT set COLOUR =”Orange” where Gcode=116;
c. Update GARMENT set COLOUR =”Orange” where Gcode is ”116”;
d. Update GARMENT where Gcode=116 set COLOUR =Orange;
Answer: b
v. What is the degree and cardinality of ‘GARMENT’ table?
a. Degree=5 & Cardinality=6
b. Degree=6 & Cardinality=5
c. Degree=5 & Cardinality=7
d. Degree=7 & Cardinality=5
Answer: a
vi. Suggest a free software for managing the database a. Oracle b. MySQL c. Sybase d. Microsoft SQL Server
Answer: b
XII – IP(2025.26) 247 Unit 2 : MySQL
Q.4. A Gift Gallery has different stores in India. Database Administrator Abhay wants to maintain database
of their Salesmen in SQL to store the data, He has decided that
Name of the database: GiftGallery
Name of the table: Salesman
Attributes of the tables: Scode – Numeric, Sname – Character 25, Address - Character 25, Dojoin - Date,
Sales – Numeric and Area – Character 10
Consider the following records in ‘Salesman’ table and answer the given questions:
Table : Salesman
i. State the command that will give the output as :
Sname
Sushant
Priya
a. Select Sname from Salesman Where Not Address =”Delhi”;
b. Select Sname from Salesman Where Address NOT IN(“Delhi”);
c. Select Sname from Salesman Where Address !=“Delhi”;
d. All of the above;
Answer: (d) All of the above
ii. Which of the following commands will display the details of all sales record of North Area, regardless of
case (whether North / NORTH / north):
a. Select * from salesman where area like upper ‘north’;
b. Select * from salesman where area = ‘North’ or ‘NORTH’ or north;
c. Select * from salesman where upper(area)=’NORTH’;
d. Select * from salesman where area= =upper(’North”)’;
Answer : (c) Select * from salesman where upper(area)=’NORTH’;
iii. Help Priya to display sname and sales of east and west areas
a. Select sname, sales from Salesman where area=”East” and area=”West”;
b. Select sname, sales from Salesman where area=”East” or area=”West”;
c. Select sname, sales from Salesman where area in ”East” and ”West”;
d. Select sname, sales from Salesman where area=”East” , ”West”;
Answer:(b) Select sname, sales from Salesman where area=”East” or area=”West”;
iv. The command to display the name of the salesman along with the sales amount rounded off to one decimal
point will be:
a. Select sname, round(sales,1) from salesman;
b. Select sname, round(sales,0.1) from salesman;
c. Select sname, trunc(sales,1) from salesman;
d. Select sname, trunc(sales,0.1) from salesman;
answer:(a) Select sname, round(sales,1) from salesman;
v. What will be the output of the following command? Select Right(Sname,3), Round(Sales) from Salesman
Where Sname Like “P%”;
XII – IP(2025.26) 248 Unit 2 : MySQL
Answer : (d)
Q.5: A Fashion Store MyStore is considering to maintain database of their Customers in SQL to store the
data, As a Database Administrator Hina has decided that
Name of the database: MyStore
Name of the table: Customer
Attributes of the tables: Acc_No – Numeric, Cust_Name – Character 25, Cust_City - Character 25,
Cust_Phone - Character 11, Open_Bal – Numeric
Consider the following records in ‘Customer’ table and answer the given questions:
Table : Customer
i. With reference to the above given table, give query for generating following output
a. Select Name from Customer where Open_bal<20000;
b. Select Name from Customer where Cust_City like ‘%a’;
c. Select Cust_Name from Customer where Cust_City like ‘%a’;
d. Select Cust_name from Customer where Cust_Name like “a%;
Answer : (c) Select Cust_Name from Customer where Cust_City like ‘%a’;
ii. Give the output of :
Select Cust_Name, Open_Bal from Customer order by Open_bal;
XII – IP(2025.26) 249 Unit 2 : MySQL
Answer : (a)
iii. Pranay has given the following command to obtain Highest Opening Balance of each City
Select max(Open_Bal) from Customer where group by Cust_City;
but he is not getting the desired result. Help him by writing the correct command.
a. Select Max(Open_Bal) group by Cust_City;
b. Select Max(Open_Bal) from Customer where group by Cust_City;
c. Select Cust_City, Max(Open_Bal) from Customer group by Cust_City;
d. Select max(Open_Bal) from Customer group by Cust_name;
Answer : (c) Select Cust_City, Max(Open_Bal) from Customer group by Cust_City;
iv. Help Pranay find the total no. of records having open_bal between 15000 to 20000 by selecting the right
command:
a. Select total from customer having open_bal between 15000 and 20000;;
b. Select count(*) from customer where open_bal between 15000 to 20000;;
c. Select count(*) from customer where open_bal between 15000 and 20000;
d. Select count(*) from customer order by open_bal;
Answer: (c) Select count(*) from customer where open_bal between 15000 and 20000;
v. Choose the correct command to display the first two letters of each customer’s name.
a. select right(cust_name,2) from customer;
b. select left(cust_name,2) from customer;
c. select right(cust_name,0,2) from customer;
d. select left(cust_name,2) from customer;
Answer: (b) select left(cust_name,2) from customer;
NCERT SUMMARY
• A Function is used to perform a particular task and return a value as a result.
• Single row functions work on a single row to return a single value.
• Multiple row functions work on a set of records as a whole and return a single value.
• Numeric functions perform operations on numeric values and return numeric values.
• String functions perform operations on character type values and return either character or numeric values.
• Date and time functions allow us to deal with date type data values.
• GROUP BY function is used to group the rows together that contain similar values in a specified column.
Some of the group functions are COUNT, MAX, MIN, AVG and SUM.
• Join is an operation which is used to combine rows from two or more tables based on one or more common
fields between them.
NCERT EXERCISE
1. Answer the following questions:
a) Define RDBMS. Name any two RDBMS software.
b) What is the purpose of the following clauses in a select statement?
i) ORDER BY ii) HAVING
c) Site any two differences between Single_row functions and Aggregate functions.
d) What do you understand by Cartesian Product?
e) Write the name of the functions to perform the following operations:
i) To display the day like “Monday”, “Tuesday”, from the date when India got independence.
ii) To display the specifi ed number of characters from a particular position of the given string.
iii) To display the name of the month in which you were born.
iv) To display your name in capital letters.
2. Write the output produced by the following SQL commands:
a) SELECT POW(2,3);
b) SELECT ROUND(123.2345, 2), ROUND(342.9234,-1);
c) SELECT LENGTH("Informatics Practices");
XII – IP(2025.26) 250 Unit 2 : MySQL
d) SELECT YEAR(“1979/11/26”), MONTH(“1979/11/26”), DAY(“1979/11/26”),
MONTHNAME(“1979/11/26”);
e) SELECT LEFT("INDIA",3), RIGHT("Computer Science",4);
f) SELECT MID("Informatics",3,4), SUBSTR("Practices",3);
3. Consider the following table named “Product”, showing details of products being sold in a grocery
shop.
a) Write SQL queries for the following:
i. Create the table Product with appropriate data types and constraints.
ii. Identify the primary key in Product.
iii. List the Product Code, Product name and price in descending order of their product name. If PName is the
same then display the data in ascending order of price.
iv. Add a new column Discount to the table Product.
v. Calculate the value of the discount in the table Product as 10 per cent of the UPrice for all those products
where the UPrice is more than 100, otherwise the discount will be 0.
vi. Increase the price by 12 per cent for all the products manufactured by Dove.
vii.Display the total number of products manufactured by each manufacturer.
b) Write the output(s) produced by executing the following queries on the basis of the information given
above in the table Product:
i. SELECT PName, Average(UPrice) FROM Product GROUP BY Pname;
ii. SELECT DISTINCT Manufacturer FROM Product;
iii. SELECT COUNT(DISTINCT PName) FROM Product;
iv. SELECT PName, MAX(UPrice), MIN(UPrice) FROM Product GROUP BY PName;
4. Using the CARSHOWROOM database given in the chapter, write the SQL queries for the following:
a) Add a new column Discount in the INVENTORY table.
b) Set appropriate discount values for all cars keeping in mind the following:
(i) No discount is available on the LXI model.
(ii) VXI model gives a 10% discount.
(iii) A 12% discount is given on cars other than LXI model and VXI model.
c) Display the name of the costliest car with fuel type “Petrol”.
d) Calculate the average discount and total discount available on Car4.
e) List the total number of cars having no discount.
5. Consider the following tables Student and Stream in the Streams_of_Students database. The primary key
of the Stream table is StCode (stream code) which is the foreign key in the Student table. The primary key of
the Student table is AdmNo (admission number).
Write SQL queries for the following:
a) Create the database Streams_Of_Students.
b) Create the table Student by choosing appropriate data types based on the data given in the table.
c) Identify the Primary keys from tables Student and Stream. Also, identify the foreign key from the table
Stream.
XII – IP(2025.26) 251 Unit 2 : MySQL
d) Jay has now changed his stream to Humanities.
Write an appropriate SQL query to reflect this change.
e) Display the names of students whose names end with the character ‘a’. Also, arrange the students in
alphabetical order.
f) Display the names of students enrolled in Science and Humanities stream, ordered by student name in
alphabetical order, then by admission number in ascending order (for duplicating names).
g) List the number of students in each stream having more than 1 student.
h) Display the names of students enrolled in different streams, where students are arranged in descending
order of admission number.
i) Show the Cartesian product on the Student and Stream table. Also mention the degree and cardinality
produced after applying the Cartesian product.
j) Add a new column ‘TeacherIncharge” in the Stream table. Insert appropriate data in each row.
k) List the names of teachers and students.
l) If Cartesian product is again applied on Student and Stream tables, what will be the degree and cardinality
of this modified table?
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) To display (student ID, marks) details of the table in descending order of the marks.
(v) To Display Name and Marks of the students whose name starts with “N”
(vi) To modify Lakshmi Marks to 90
(vii) Delete the details of student with studentid-W1003 in the above table.
(viii) To insert a new row with details [W1006,Anand,80]
Write Outputs on the original given data:
(ix) SELECT LCASE(NAME) FROM STUDENT WHERE MARKS>75;
(To display the student names in lower case letters, whose marks are more than 75)
(x) SELECT NAME, LENGTH(NAME) FROM STUDENT;
(To display student name, along with its length (count of number of characters))
(xi) SELECT NAME, INSTR(NAME,"a") FROM STUDENT;
(To display student name, along with position of character “a” in name)
(xii) SELECT STUDENTID,NAME,LEFT(NAME,3) FROM STUDENT;
(To display student id, Name and first three characters of the name)
(xiii) SELECT MIN(MARKS),MAX(MARKS),SUM(MARKS),AVG(MARKS),COUNT(NAME),
COUNT(*) FROM STUDENT;
(To display min, max, sum, and average of the marks, count of names, count of rows in student table.)
(xiv) SELECT NAME, SUBSTR(NAME,2,3) FROM STUDENT;
(To display name, 2nd character onwards 3 characters from Name)
Answers:
(i) CREATE TABLE STUDENT(STUDENTID VARCHAR(5) PRIMARY KEY,NAME
VARCHAR(30),MARKS FLOAT);
Output:
XII – IP(2025.26) 252 Unit 2 : MySQL
(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 STUDENTID, MARKS FROM STUDENT ORDER BY MARKS DESC;
Output:
(v) SELECT NAME,MARKS FROM STUDENT WHERE NAME LIKE "N%";
Output:
(vii) UPDATE STUDENT SET MARKS=90 WHERE NAME='LAKSHMI';
Output:
(vii) DELETE FROM STUDENT WHERE STUDENTID='W1003';
Output:
(viii) INSERT INTO STUDENT VALUES('W1006','Anand',80);
Output:
XII – IP(2025.26) 253 Unit 2 : MySQL
Outputs:
(ix)
(x)
(xi)
(xii)
(xiii)
(xiv)
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) To display CustomerID and CustomerName in ascending order of CustomerName.
(iv) To Display the details of the customers whose country name ends with “IA”
(v) To change the Country of Mohan to Africa.
(vi) Find the total number of customers from each country in the table using group by.
(vii) Delete the entire customers table including structure.
Write Outputs on the original given data:
(viii) SELECT CUSTOMERNAME, LEFT(CUSTOMERNAME,3),RIGHT(COUNTRY,2) FROM
CUSTOMERS;
(Display CustomerName,first 3 characters from CustomerName and last 3 characters from Country.)
XII – IP(2025.26) 254 Unit 2 : MySQL
(ix) SELECT UCASE(CUSTOMERNAME), LCASE(COUNTRY) FROM CUSTOMERS;
(To display the cutomernames in upper case letters and Country names in lower case letters.)
(x) SELECT CUSTOMERNAME,LEFT(MID(CUSTOMERNAME,2,4),2) FROM CUSTOMERS;
(xi) SELECT COUNTRY, LENGTH(COUNTRY) FROM CUSTOMERS;
(To display Country Name along with count of characters in country name)
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:
(iii) SELECT CUSTOMERID,CUSTOMERNAME FROM CUSTOMERS ORDER BY
CUSTOMERNAME ASC;
Output:
(iv) SELECT * FROM CUSTOMERS WHERE COUNTRY LIKE "%ia";
Output:
(v) UPDATE CUSTOMERS SET COUNTRY="AFRICA" WHERE CUSTOMERNAME="MOHAN";
Output:
(vi) SELECT COUNTRY, COUNT(*) FROM CUSTOMERS GROUP BY COUNTRY;
Output:
(vii) DROP TABLE CUSTOMERS;
Output:
XII – IP(2025.26) 255 Unit 2 : MySQL
(viii)
(ix)
(x)
(xi)
23. Consider the following table “Faculty”.
SNo Name Subject DOJ Salary
1 Naveen Babu IP 2019-12- 65759
25
2 Suman Suresh ICT 2015-10- 53460
18
3 Swathi Latha AI 2020-05- 62724
10
4 Gayathri Kumari IP 2020-03- 45690
15
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.
(xi) To display Name,DOJ and their joining month name.
Write outputs for the following SQL Queries:
(xii) SELECT NAME,POWER(SNO,3) FROM FACULTY;
(xiii) SELECT NAME,SALARY,ROUND(SALARY,-2) FROM FACULTY;
(xiv) SELECT MOD(SALARY,SNO) FROM FACULTY;
(xv) SELECT MID(RIGHT(NAME,4),2) FROM FACULTY;
(xvi) SELECT INSTR(NAME,’A’) FROM FACULTY;
XII – IP(2025.26) 256 Unit 2 : MySQL
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:
(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';
XII – IP(2025.26) 257 Unit 2 : MySQL
(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:
(xi) SELECT NAME,DOJ, MONTHNAME(DOJ) FROM FACULTY;
OUTPUTS
(xii)
(xiii)
(xiv)
(xv)
(xiv)
XII – IP(2025.26) 258 Unit 2 : MySQL
XII – IP – MySQL – Worksheet
VEG Table
Write SQL statements/Queries for the following:
1) To create the above table
create table veg(vnumber varchar(3) primary key,vname varchar(20),price int,DOP date,category
varchar(10));
2) In Insert the above values
insert into veg values('V1','Brinjal',60,'2025-01-15','Non Leafy'),('V2','Onion',40,'2024-12-10','Non Leafy'),
('V3','Spinach',10,'2025-02-15','Leafy'), ('V4','Potato',30,'2024-01-30','Non Leafy'), ('V5','Chilly',50,'2025-
01-25','Non Leafy'), ('V6','Coriander',20,'2025-02-15','Leafy');
3) To see the structure of the table
DESC VEG;
4) To see all the details of the table
SELECT * FROM VEG;
5) To display vegetable names and their categories.
SELECT VNAME,CATEGORY FROM VEG;
6) To display vegetable names and their double price.
SELECT VNAME,PRICE*2 AS "DOUBLE PRICE" FROM VEG;
7) To display details of Leafy vegetables only.
SELECT * FROM VEG WHERE CATEGORY="LEAFY";
8) To display vegetable number and vegetable name whose price is more than 30;
SELECT VNUMBER,VNAME FROM VEG WHERE PRICE>30;
XII – IP(2025.26) 259 Unit 2 : MySQL
9) To display vegetable names whose price is from 20 to 50. (Without using Between)
SELECT VNAME FROM VEG WHERE PRICE >=20 AND PRICE<=50;
10) To display vegetable names and their prices whose price is from 30 to 60. (Use Between Keyword)
SELECT VNAME,PRICE FROM VEG WHERE PRICE BETWEEN 30 AND 60;
11) To display vegetable number and vegetable name which are purchased after 20th January 2025.
SELECT VNUMBER,VNAME FROM VEG WHERE DOP>'2025-01-20';
12) To display vegetable number and vegetable name, whose vegetable numbers are V1, V2 and V3.
(use IN)
SELECT VNUMBER,VNAME FROM VEG WHERE VNUMBER IN('V1','V3','V5');
13) To display vegetable names and their prices, whose vegetable name starts with c.
SELECT VNAME,PRICE FROM VEG WHERE VNAME LIKE 'C%';
14) To display vegetable names, whose second character is “O”.
SELECT VNAME FROM VEG WHERE VNAME LIKE '_O%';
15) To display different categories list
SELECT DISTINCT(CATEGORY) FROM VEG;
XII – IP(2025.26) 260 Unit 2 : MySQL
16) To display all categories list
SELECT ALL CATEGORY FROM VEG;
17) To display vegetable names and prices in the ascending order of price.
SELECT VNAME,PRICE FROM VEG ORDER BY PRICE;
18) To display vegetable names and prices in the descending order of vegetable names.
SELECT VNAME,PRICE FROM VEG ORDER BY VNAME DESC;
ALTER TABLE
19. To add a column “Colour” with datatype “varchar” to store 10 characters.
ALTER TABLE VEG ADD COLUMN COLOUR VARCHAR(10);
SELECT * FROM VEG;
20. To remove primary key of the table.
ALTER TABLE VEG DROP PRIMARY KEY;
DESC VEG;
21. To add primary key (vnumber)
ALTER TABLE VEG ADD PRIMARY KEY(VNUMBER);
DESC VEG;
22. To remove the column “Colour”
ALTER TABLE DROP COLUMN COLOUR;
XII – IP(2025.26) 261 Unit 2 : MySQL
DESC VEG;
23. To change the datatype of price to float.
ALTER TABLE VEG MODIFY COLUMN PRICE FLOAT;
DESC VEG;
24. To change the attribute name vname to “vegetablename” and its datatype is varchar(30).
ALTER TABLE VEG CHANGE COLUMN VNAME VEGETABLENAME VARCHAR(30);
DESC VEG;
UPDATE, DELETE & DROP
25. To change the price of Spinach to 15.
UPDATE VEG SET PRICE=15 WHERE VNAME='SPINACH';
SELECT * FROM VEG;
26. To delete V1 and V3 vegetables details.
DELETE FROM VEG WHERE VNUMBER IN ('V1','V3');
SELECT * FROM VEG;
27. To delete all vegetable details.
DELETE FROM VEG;
28. To delete entire table (including the structure)
DROP TABLE VEG;
NUMERIC FUNCTIONS (3)
Pow( ), Round( ), Mod( )
1) (A) To get the squares of Prices.
SELECT POW(PRICE,2) FROM VEG;
XII – IP(2025.26) 262 Unit 2 : MySQL
(B) To get the value 73.
SELECT POW(7,3);
2) To get the Reminder of the expression 15 divided by 7.
SELECT MOD(15,7);
3) Write Output of the following statements.
(A)
SELECT ROUND(74628.68523,1) 74628.7
SELECT ROUND(74628.68523,2) 74628.69
SELECT ROUND(74628.68523,3); 74628.685
SELECT ROUND(74628.68523,4); 74628.6852
SELECT ROUND(74628.68523,5); 74628.68523
SELECT ROUND(74628.68523,6); 74628.685230
SELECT ROUND(74628.68523,0); 74629
SELECT ROUND(74628.68523); 74629
SELECT ROUND(74628.68523,-1); 74630
SELECT ROUND(74628.68523,-2); 74600
SELECT ROUND(74628.68523,-3); 75000
SELECT ROUND(74628.68523,-4); 70000
SELECT ROUND(74628.68523,-5); 100000
SELECT ROUND(74628.68523,-6); 0
Text Functions (10)
Ucase( )/Upper( ), Lcase( )/Lower( ), Mid( )/Substring( )/Substr( ), Length( ), Left( ), Right( ), Instr( ),
Ltrim( ), Rtrim( ), Trim( ).
1)(A) To display Vegetable Names in capital letters
SELECT UCASE(VNAME) FROM VEG;
(B) To display the string “Welcome to AP” in capital letters
SELECT UPPER("Welcome to AP");
2) (A) To display Category in lower case letters.
SELECT LCASE(CATEGORY) FROM VEG;
(B) To display the string “Welcome to AP” in lower case letters.
SELECT LOWER("Welcome to AP");
XII – IP(2025.26) 263 Unit 2 : MySQL
3) (A) To display 2nd character onwards totally 3 characters in vegetable names
(Vegetable names also should display)
SELECT VNAME,SUBSTRING(VNAME,2,3) FROM VEG;
SELECT VNAME,SUBSTR(VNAME,2,3) FROM VEG;
SELECT VNAME,MID(VNAME,2,3) FROM VEG;
SELECT SUBSTR("Welcome to AP",4,7);
SELECT MID("Welcome to AP",4);
4) (A) To display length of vname, price and DOP
SELECT VNAME,LENGTH(VNAME),PRICE,LENGTH(PRICE), DOP,LENGTH(DOP) FROM VEG;
(B) To display length of “India is best country”.
SELECT LENGTH("INDIA is best country");
(5) (A) To display first 3 characters in vegetable names.
SELECT LEFT(VNAME,3) FROM VEG;
XII – IP(2025.26) 264 Unit 2 : MySQL
SELECT SUBSTR(VNAME,1,3) FROM VEG;
(B) To display first 10 characters from “INDIA is best country”.
SELECT LEFT("INDIA is best country",10);
DATE/TIME FUNCTIONS (7)
Now( ), Date( ), Month( ), MonthName( ), Year( ), Day( ), DayName( )
1. Get the current date and time using NOW()
SELECT NOW() AS Current_DateTime;
2. Get only the current date using DATE()
SELECT DATE(NOW()) AS Current_Date;
3. Extract the month from the DOP column using MONTH()
SELECT vname, DOP, MONTH(DOP) AS Month_Number FROM Veg;
4. Get the month name from DOP using MONTHNAME()
SELECT vname, DOP, MONTHNAME(DOP) AS Month_Name FROM Veg;
5. Extract the year from DOP using YEAR()
SELECT vname, DOP, YEAR(DOP) AS Year_Value FROM Veg;
XII – IP(2025.26) 265 Unit 2 : MySQL
6. Extract the day of the month from DOP using DAY()
SELECT vname, DOP, DAY(DOP) AS Day_Number FROM Veg;
7. Get the weekday name from DOP using DAYNAME()
SELECT vname, DOP, DAYNAME(DOP) AS Day_Name FROM Veg;
8. Get all vegetables that were purchased in January
SELECT vname, DOP FROM Veg WHERE MONTH(DOP) = 1;
9. Get vegetables purchased on a Saturday
SELECT vname, DOP FROM Veg WHERE DAYNAME(DOP) = 'Saturday';
10. Get the vegetables that were purchased in the current year (assuming current year is 2025)
SELECT vname, DOP FROM Veg WHERE YEAR(DOP) = YEAR(NOW());
COMBINATION OF THESE FUNCTIONS
Outputs:
XII – IP(2025.26) 266 Unit 2 : MySQL
(1) SELECT VNAME, RIGHT(SUBSTR(VNAME,2,4),3) FROM VEG;
(2) SELECT POW(RIGHT(VNUMBER,1),2) FROM VEG;
(3) SELECT VNAME, UCASE(LEFT(MID(VNAME,2),4)) AS RESULT FROM VEG WHERE
PRICE>45;
(4) SELECT VNAME, MOD(LENGTH(UCASE(MID(VNAME,2))),2) AS RESULT FROM VEG;
XII – IP(2025.26) 267 Unit 2 : MySQL