Informatics Practices · Class 12 Optional
Ch 2Data Handling using Pandas – I — Class 12 Informatics Practices, concept-first.
A Python library is a collection of built-in modules that let you perform many actions without writing detailed programs from scratch. Each library contains a large number of modules that you can import and use as needed. For scientific and analytical work, three libraries stand out: NumPy, Pandas, and Matplotlib.
Key concepts
Hover a concept to preview it and jump to its most relevant Q&A.
Pandas Series Creation
Imagine you have a messy desk with loose notes, receipts, and to-do lists scattered everywhere. Now imagine you take a single strip of paper, write one item on each line in a fixed order, and label the strip "Monday's Ex…
Most relevant Q&A
- Create a series having names of any five famous monuments of India and assign their States as index values.Preview
- Write the statement to get NewDelhi as output using positional index. [Context: In the textbook, seriesCapCntry = pd.Series(['NewDelhi', 'Wa…Preview
- 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['Fou…Preview
- The Python code written below has syntactical errors. Rewrite the correct code and underline the correction(s) made. import Pandas as pd stu…Preview
- What will be the output of the following code? import pandas as pd myser = pd.Series([0, 0, 0]) print(myser) (A) 0 0 0 0 0 0 (B) 0 1 0 1 0 2…Preview
Chapter contents
The NCERT structure, section by section. Open a section to see its questions, then read the concept-first solution.
Introduction to Python Libraries
A Python library is a collection of built-in modules that let you perform many actions without writing detailed programs from scratch.
Installing Pandas
Installing Pandas is very similar to installing NumPy. Both libraries are external to Python, meaning they are not part of the standard library that comes with a fresh Python installation.
Data Structure in Pandas
A data structure is simply a way to organise data so that it can be stored, accessed, and changed efficiently. You have already seen one such structure in NumPy — the ndarray.
Series
A Series is the most basic data structure in Pandas. Think of it as a single column of data, like one column in an Excel spreadsheet.
Creation of Series
There are different ways in which a Series can be created in Pandas. Whichever way we choose, the first step is always the same: to create or use a Series, we must first import the Pandas library.
Creation of Series from Scalar Values
2 QThe simplest way to build a Series is directly from scalar values — a plain Python list of data items passed to pd.Series():
+−Activities1 question
Creation of Series from NumPy Arrays
A Series can also be created from a one-dimensional (1D) NumPy array. NumPy is imported alongside Pandas (conventionally with the alias np), the array is built with np.array(), and the array object is…
Creation of Series from Dictionary
Recall that a Python dictionary stores key: value pairs, and a value can be quickly retrieved when its key is known.
Accessing Elements of a Series
Once a Series has been created, we need ways to get at its contents. There are two common ways of accessing the elements of a Series: indexing and slicing.
Indexing
Indexing is the mechanism for accessing individual elements of a Series, and it works very much like indexing on NumPy arrays. Pandas supports two kinds of indexes:
Slicing
Sometimes we need only a part of a Series rather than a single element or the whole thing. Extracting a contiguous portion is called slicing, and it works like slicing on NumPy arrays: we specify star…
Attributes of Series
A Series object in Pandas is more than just a labelled array — it carries several built-in properties, called attributes, that let you inspect or label the data directly.
Methods of Series
A Pandas Series comes with built-in methods that let you quickly inspect, summarise, and manipulate your data. These methods save you from writing loops or manual slicing.
Mathematical Operations on Series
In Class XI we saw that basic mathematical operations — addition, subtraction, multiplication, division, and so on — applied to two NumPy arrays act on each corresponding pair of elements.
Addition of two Series
Two Series can be added in two ways.
Subtraction of two Series
Subtraction, like addition, can be done in two different ways.
Multiplication of two Series
Multiplication of two Series follows the same two-way pattern.
Division of two Series
Division of two Series, once again, can be done in two different ways.
DataFrame
A DataFrame is what you reach for when a single Series — one column of data — is not enough. Real-world data is tabular: a mark sheet with student names, subjects, and marks; a restaurant menu with it…
Creation of DataFrame
There are a number of ways to create a DataFrame, and this section lists some of them. Each of the lettered sub-sections that follow demonstrates one creation method with working code and its output.
Creation of an empty DataFrame
The simplest DataFrame of all is an empty one — no columns, no rows. It is created by calling the DataFrame() constructor with no arguments:
Creation of DataFrame from NumPy ndarrays
Pandas can build a DataFrame directly from NumPy ndarrays. To try this, first import NumPy and create three arrays:
Creation of DataFrame from List of Dictionaries
A DataFrame can also be created from a list of dictionaries. Each dictionary in the list becomes one row of the DataFrame:
Creation of DataFrame from Dictionary of Lists
DataFrames can also be created from a dictionary of lists. Here each key of the dictionary names a column, and the list stored against that key supplies the values going down that column.
Creation of DataFrame from Series
A DataFrame can be created from one or more Series. Consider the following three Series (note that seriesC deliberately uses a different set of index labels):
Creation of DataFrame from Dictionary of Series
A dictionary of Series can also be used to create a DataFrame. The textbook's example is ResultSheet, a dictionary of Series holding the marks of 5 students in three subjects.
Operations on Rows and Columns in DataFrames
Once a DataFrame exists, we are not stuck with it as-is. We can perform some basic operations on its rows and columns — selection, deletion, addition, and renaming — and this section works through eac…
Adding a New Column to a DataFrame
Adding a new column to a DataFrame is as simple as assigning a list of values to a new column label. Consider the DataFrame ResultDF defined earlier (5 students × 3 subjects).
Adding a New Row to a DataFrame
A new row is added to a DataFrame using the DataFrame.loc[] method. Consider ResultDF, which has three rows for the three subjects — Maths, Science and Hindi:
+−Think & Reflect1 question
Deleting Rows or Columns from a DataFrame
Rows and columns are deleted from a DataFrame with the DataFrame.drop() method. We need to tell it two things: the names of the labels to be dropped, and the axis from which they are to be dropped — a…
Renaming Row Labels of a DataFrame
Once a DataFrame has been created, we are not stuck with the row labels it was given — Pandas lets us change the labels of rows (and columns) using the DataFrame.rename() method.
+−Think & Reflect1 question
Renaming Column Labels of a DataFrame
The same rename() method that renames row labels also renames column labels — the only change is the axis.
Accessing DataFrames Element through Indexing
Individual data elements in a DataFrame can be accessed using indexing. Pandas offers two ways of indexing DataFrames: label based indexing, where we pick out data by the names of rows and columns, an…
Label Based Indexing
Pandas provides several methods for label based indexing, and the most important of them for DataFrames is DataFrame.loc[ ].
+−Think & Reflect1 question
Boolean Indexing
Boolean means a binary variable that can represent either of two states — True (indicated by 1) or False (indicated by 0).
Accessing DataFrames Element through Slicing
Slicing is a powerful way to select a subset of rows and/or columns from a DataFrame. Unlike Python lists, slicing in DataFrames is inclusive of the end value — meaning both the start and the stop lab…
Filtering Rows in DataFrames
Filtering rows in a DataFrame using .loc[] can also be done with a Boolean list — a list of True/False values, one per row, in the same order as the DataFrame's rows.
Joining, Merging and Concatenation of DataFrames
Pandas lets us combine the data of two DataFrames into one. Although this section's title names joining, merging and concatenation together, the textbook (Reprint 2026-27) works these out through a si…
Joining
The pandas.DataFrame.append() method is used to merge two DataFrames: it appends the rows of the second DataFrame at the end of the first.
+−Think & Reflect1 question
Attributes of DataFrames
python ForestArea = 'Assam' : pd.Series([78438, 2797, 10192, 15116], index = ['GeoArea', 'VeryDense', 'ModeratelyDense', 'OpenForest']), 'Kerala' : pd.Series([38852, 1663, 9407, 9251], index = ['Geo…
Importing and Exporting Data between CSV Files and DataFrames
We often have data stored in CSV (Comma Separated Values) files — a very common format for spreadsheets and databases.
Importing a CSV file to a DataFrame
A CSV (Comma Separated Values) file stores tabular data as plain text, where each line is a row and values are separated by commas.
Exporting a DataFrame to a CSV file
After you have created, cleaned, or processed a DataFrame in Python, you often need to save it for later use — either to share with others, to open in a spreadsheet like Excel, or to load into another…
Pandas Series Vs NumPy ndarray
The fundamental difference between a Pandas Series and a NumPy ndarray is not about speed or memory — it is about identity. A NumPy array is a grid of numbers accessed by their integer position.
Summary
This chapter covered the two core Pandas data structures and how to move data between them and CSV files.
Exercises
+−Show 11 questionsHide questions11 questions
- Q1What is a Series and how is it different from a 1-D array, a list and a dictionary?Free
- Q2What is a DataFrame and how is it different from a 2-D array?Free
- Q3How are DataFrames related to Series?Free
- Q4What do you understand by the size of (i) a Series, (ii) a DataFrame?Preview
- Q5Create the following Series and do the specified operations: a) EngAlph, having 26 elements with the alphabets as values and default index v…Preview
- Q6Using 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) D…Preview
- Q7Using the Series created in Question 5, write commands for the following: a) Find the dimensions, size and values of the Series EngAlph, Vow…Preview
- Q8Using the Series created in Question 5, write commands for the following: a) Display the names of the months 3 through 7 from the Series Mon…Preview
- Q9Create the following DataFrame Sales containing year wise sales figures for five sales persons in INR. Use the years as column labels, and s…Preview
- Q10Use 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…Preview
- Q11Use the DataFrame created in Question 9 above to do the following: a) Append the DataFrame Sales2 to the DataFrame Sales. b) Change the Data…Preview
CBSE Sample Papers
Questions from official CBSE sample papers.
+−Show 11 questionsHide questions11 questions
- Q1What 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['Fou…Preview
- Q2The Python code written below has syntactical errors. Rewrite the correct code and underline the correction(s) made. import Pandas as pd stu…Preview
- Q3Find the output of the following Python code : import pandas as pd com=pd.Series([45,12,15,200],index=['mouse','printer','webcam','keyboard'…Preview
- Q4State whether the following statement is True or False : In Pandas Series, the Positional index can be a string or an integer.Preview
- Q5In Pandas, when extracting a portion of a Series ser1 using ser1[start:end] with positional indices start and end, which of the following st…Preview
- Q6What will be the output of the following code? import pandas as pd myser = pd.Series([0, 0, 0]) print(myser) (A) 0 0 0 0 0 0 (B) 0 1 0 1 0 2…Preview
- Q7Assertion (A) : The output of addition of two series will be NaN, if one of the elements or both the elements have no value(s). Reason (R) :…Preview
- Q8Write a Python program to create a series object, country using a list that stores the capital of each country. Note: Assume four countries…Preview
- Q9What is the default index type for a Pandas Series if not explicitly specified? (A) String (B) List (C) Numeric (D) BooleanPreview
- Q10Which of the following Python statements will be used to select a specific element having index as points, from a Pandas Series named ser? (…Preview
- Q11Which of the following libraries defines an ndarray in Python? (A) pandas (B) numpy (C) matplotlib (D) scipyPreview