Data Handling Using Pandas I Class 12 Notes

Need Data Handling Using Pandas I Class 12 notes that actually hold up when you revise? This page distils Chapter 2 of the NCERT Informatics Practices textbook — Series, DataFrame, CSV transfer and the Series-versus-ndarray comparison — into one revision document you can work through in a single sitting.

Every concept is defined first, then shown as syntax, then demonstrated with fresh output, so you never have to guess what a statement prints. These notes follow the 2026-27 session.

The chapter’s ideas build in a strict order: a Series is the one-dimensional building block, a DataFrame is built from Series, and only then do CSV import/export make sense. This page keeps that order. Read the one-glance map, fix the key terms, then work the two worked examples with original numbers before you touch the syntax quick reference.

Who is this for? A Class 12 Informatics Practices student revising before a class assessment or the board exam — or before a practical lab session. You can find this page through the CBSE notes library, and for the wider set of chapters, browse the Class 12 notes index or the Class 12 Informatics Practices notes hub.

Pandas I in One Glance: Series, DataFrame and CSV

The chapter runs from page 27 to page 62 of the NCERT Informatics Practices book, and this page condenses all five blocks of it: Python libraries, Series, DataFrame, importing and exporting data between CSV files and DataFrames, and Pandas Series vs NumPy ndarray.

The blocks depend on each other in a fixed build order:

  • Python libraries first — you must import pandas before any of this works.
  • Series next — the one-dimensional labelled structure is the smallest building block.
  • DataFrame after that — a DataFrame is assembled from Series, so Series has to be clear first.
  • CSV import/export last — reading and writing files only makes sense once DataFrames exist.
  • Series vs ndarray closes the chapter — it positions what you learned in Class XI (NumPy arrays) against Pandas.

By the end of the chapter you should be able to: create a Series from four data sources, create a DataFrame from six, index/slice/filter/modify both, and move a DataFrame to and from a CSV file.

The same textbook continues this Pandas work in its Data Handling Using Pandas II chapter, which has its own separate notes on this site.

Key Terms: Definitions That Recur in Every Question

Fix these fourteen terms first — they appear in almost every code exercise. Each meaning is in simple words, with a fresh example you can reproduce.

Term Meaning in simple words Example
Python library A collection of built-in modules you can import, so common tasks do not need programs written from scratch. import pandas as pd
data structure A collection of data values plus the operations that can act on that data; makes storage, retrieval and modification efficient. ndarray in NumPy
Series A one-dimensional labelled array holding a sequence of values of any data type. pd.Series([32, 35, 31])
index The data label attached to each value of a Series. 0, 1, 2 by default
positional index An integer label equal to an element’s position, counting from 0. temps[2] gives the third value
labelled index A user-defined label used to identify an element. index=['Feb', 'Mar', 'Apr']
DataFrame A two-dimensional labelled structure with row and column labels, like a spreadsheet. pd.DataFrame({'City': ['Pune', 'Jaipur']})
NaN Not a Number — Pandas’ marker for a missing value. appears where two Series have no matching label
attribute A property of an object, read as object.attribute. temps.size
method A function attached to an object, called as object.method(). temps.count()
CSV Comma-Separated Value file: a text file whose lines are records with comma-separated fields. ResultData.csv
alignment Matching values between two Series operations by index label rather than by position. s1 + s2 matches labels
boolean indexing Filtering data with a condition that evaluates each value to True or False. df['Maths'] > 88
transpose Swapping the row labels and column labels of a DataFrame. ForestAreaDF.T

NumPy, Pandas and Matplotlib: What Each One Does

A Python library is a collection of built-in modules that let you perform many actions without writing detailed programs for each one (NCERT, p. 27). Three scientific libraries matter here:

  • NumPy (Numerical Python) — numerical data analysis and scientific computing built around a multidimensional array object; elements stay together in memory, so they are accessed quickly.
  • Pandas (PANel Data) — a high-level data manipulation tool for analysing data; it is built on NumPy and Matplotlib, has a rich function set for importing/exporting data, and offers three data structures: Series, DataFrame and Panel.
  • Matplotlib — plotting and visualisation: publication-quality plots, histograms, bar charts and scatterplots in a few lines of code (NCERT, p. 28).

Installation requires Python first; then run pip install pandas (NCERT, p. 28). Why use Pandas at all when NumPy exists? Four practical differences:

  • A NumPy array needs homogeneous data; a Pandas DataFrame can hold float, int, string, datetime and other types in different columns.
  • Pandas has a simpler interface for file loading, plotting, selection, joining and GROUP BY.
  • DataFrames carry column names, which makes keeping track of data easy.
  • Pandas suits tabular format data; NumPy suits numeric array-based manipulation (NCERT, p. 28).

Think and Reflect (p. 30): the alias pd is a convention, not a rule. Any valid Python identifier works — for example import pandas as pnd — as long as you use the same name everywhere.

Series: The One-Dimensional Workhorse

A Series is a one-dimensional labelled array containing a sequence of values of any data type — int, float, list, string and so on (NCERT, p. 29). The label attached to each value is its index. If you do not supply an index, Pandas numbers the values from \(0\) to \(N – 1\), where \(N\) is the number of elements.

import pandas as pd
temps = pd.Series([32, 35, 31, 29])
print(temps)

The printed output has two columns: index on the left, value on the right, and a final line stating the dtype:

0    32
1    35
2    31
3    29
dtype: int64

Imagine a Series as one labelled column of a spreadsheet — the labels are the row positions and the column holds one type of value.

Creating a Series: Data Sources and Their Indexes

All creation starts with import pandas as pd. What becomes the index depends entirely on the source (NCERT, pp. 29-31):

Source Syntax pattern What becomes the index Notes
List of scalar values pd.Series([10, 20, 30]) default 0 to N-1 dtype is inferred from the values
1-D NumPy array pd.Series(array1, index=['Jan', 'Feb', 'Mar', 'Apr']) the labels you pass; default range if no index is given index length must equal array length, else ValueError
Dictionary pd.Series(dict1) the dictionary keys the dictionary values become the data
Empty pd.Series() none empty attribute returns True

The critical length rule: when an index is passed with an array, the number of labels must match the number of values. Four values with three labels raise ValueError: Length of passed values is 4, index implies 3 (NCERT, p. 31).

For a dictionary such as {'India': 'NewDelhi', 'UK': 'London', 'Japan': 'Tokyo'}, the keys become the index and the capitals become the values. The dtype (int64, int32, object, …) is inferred from the data itself.

Indexing and Slicing a Series: Label vs Position

There are two kinds of index (NCERT, p. 31): a positional index, an integer matching the element’s position starting at 0, and a labelled index, any user-defined label. The choice changes how slicing behaves.

The slice inclusion rule — the most asked distinction in the chapter (NCERT, p. 33):

  • Positional slice sr[1:3] — the end position is excluded; only positions 1 and 2 come out.
  • Labelled slice sr['Feb':'Apr'] — the end label is included; Feb, Mar and Apr all come out.

Memory device: the word “labelled” has two fewer letters than “positional” — yet a labelled slice carries one more value. L-abelled means L-onger: labels include the end; positional slices stop short of it.

Other access facts from the same pages:

  • A single label returns one value (sr['Mar'] gives 3); a list of labels returns a Series (sr[['Feb', 'Apr']]).
  • Reverse the whole Series with sr[::-1].
  • Slice assignment follows the same rule: sr[1:3] = 50 changes positions 1 and 2 only, while sr['c':'e'] = 500 changes labels c, d and e — the end label is included (NCERT, p. 34).
  • The index itself can be replaced: sr.index = [10, 20, 30, 40].

Series Attributes and Methods: Quick Properties You Can Query

Attributes are properties you read with the object; methods are actions you call. The table covers the ones that appear in short-answer questions (NCERT, pp. 34-35).

Name Type What it does
name attribute Names the Series; the name prints in the output header (Name: …).
index.name attribute Names the index; prints above the index column.
values attribute Returns the values alone, without labels.
size attribute The number of values in the Series.
empty attribute True for an empty Series, False otherwise.
head(n) method First n values; n defaults to 5 when omitted.
tail(n) method Last n values; n defaults to 5 when omitted.
count() method Number of non-NaN values — not the total length.

Activity 2.3 (p. 35): for a Series containing 12, NaN and 10, the statement that counts and displays only non-null values is simply s2.count() — it ignores the NaN and reports 2.

Mathematical Operations on Series: Alignment, NaN and fill_value

The core idea: adding, subtracting, multiplying or dividing two Series matches values by index label, never by position (NCERT, p. 36). When a label exists in only one of the two Series, Pandas fills the missing side with NaN so the operation never fails.

There are two ways to operate:

  • Operators: seriesA + seriesB, seriesA - seriesB, seriesA * seriesB, seriesA / seriesB. Missing labels produce NaN in the output, and the result’s dtype becomes float64.
  • Methods: seriesA.add(seriesB), sub(), mul(), div(). The method form accepts fill_value, which replaces the missing value with a number you choose before calculating (NCERT, pp. 37-39).

Explicit methods are preferred when the Series may have missing values, because fill_value gives a concrete numeric output in place of NaN (NCERT, p. 39). The full operator-versus-method comparison with original numbers is worked out in the Worked Examples section below.

DataFrame: A Spreadsheet You Can Code

A DataFrame is a two-dimensional labelled data structure with both row labels and column labels — a table or spreadsheet you can manipulate in code (NCERT, p. 40). Each column can hold a different data type: integers in one column, strings in another, floats in a third, all inside the same DataFrame.

It suits the tabular data you meet everywhere: class results, restaurant menus, train reservation charts.

The mental model that runs through the whole chapter: a DataFrame is a dictionary of Series that share the same index — or equivalently, a dictionary of lists. Keeping that in mind makes every creation method predictable. A quick preview:

import pandas as pd
shop = pd.DataFrame({
    'Item': ['Notebook', 'Pen', 'Eraser'],
    'Price': [40, 10, 5]
})
print(shop)
      Item  Price
0  Notebook     40
1       Pen     10
2    Eraser      5

Rows are labelled 0, 1, 2 by default, and the dictionary keys Item and Price became the column labels.

Creating a DataFrame: Six Data Sources

Pandas builds a DataFrame from six kinds of input (NCERT, pp. 40-44). For each one, notice who decides the row labels and the column labels, and when NaN appears.

Source Syntax pattern Row labels Column labels When NaN appears
Empty DataFrame pd.DataFrame() none none never — it is a blank frame
Single NumPy ndarray pd.DataFrame(array1) default 0 to n-1 one column labelled 0 never
Several NumPy ndarrays pd.DataFrame([a1, a3, a2], columns=['A', 'B', 'C', 'D']) default 0 to n-1 the columns parameter, or integers wherever an array is shorter than the widest array
List of dictionaries pd.DataFrame(listDict) one row per dictionary the dictionary keys a key missing from one dictionary
Dictionary of lists pd.DataFrame(dictForest) default 0 to n-1 the dictionary keys not shown in the chapter’s equal-length examples
Single Series / list of Series pd.DataFrame(seriesA) / pd.DataFrame([sA, sB]) single Series: its index labels; list: one default row per Series single Series: one column labelled 0; list: the Union of Series labels when the Series have different label sets
Dictionary of Series pd.DataFrame(ResultSheet) the union of all Series indexes the dictionary keys a Series lacking a label that another Series has

Three extra rules to remember:

  • The columns parameter reorders columns: pd.DataFrame(dictForest, columns=['State', 'VDF', 'GArea']) places VDF before GArea (NCERT, p. 42).
  • From a list of dictionaries, the column count equals the maximum number of keys in any dictionary (NCERT, pp. 41-42).
  • From a dictionary of Series, the resulting index is the union of all the Series indexes, and missing cells become NaN (NCERT, p. 43). Notice the difference: when the dictionary values are lists, keys become columns with a default row index; when the values are Series, keys still become columns but the rows come from all the Series labels together.

Adding, Updating, Deleting and Renaming Rows and Columns

The chapter’s exercises lean heavily on these row/column operations (NCERT, pp. 44-49). The mechanism differs by direction, so keep each rule separate:

Operation Statement Rule
Add a column df['Preeti'] = [89, 78, 76] New label -> column appended at the end; existing label -> values updated.
Rewrite a whole column or row df['Arnab'] = 90 or df.loc['Maths'] = 0 Replaces every value in that column or row.
Add a row df.loc['English'] = [85, 86, 83] List length must equal the number of columns.
Update an existing row df.loc['English'] = [95, 86, 95] A duplicate row label updates the existing row; it does not insert a second row.
Set all values df[:] = 0 Every cell becomes 0.
Delete rows df.drop('Science', axis=0) axis=0 is rows; when labels are duplicated, all matching rows are deleted.
Delete columns df.drop(['Samridhi', 'Ramit'], axis=1) axis=1 is columns.
Rename rows df.rename({'Maths': 'Sub1'}, axis='index') Labels not given a new name stay unchanged.
Rename columns df.rename({'Arnab': 'Student1'}, axis='columns') Same rule — only mapped labels change.

Two ValueErrors from page 46 to memorise:

  • Adding a row with fewer values than columns -> ValueError: Cannot set a row with mismatched columns.
  • Adding a column with fewer values than rows -> ValueError: Length of values does not match length of index.

Also note that drop() removes all matching rows when the row label is duplicated (NCERT, p. 47).

Accessing DataFrame Data: loc, Boolean Indexing and Slicing

df.loc[] is the chapter’s label-based access method for DataFrames (NCERT, p. 49). What comes back depends on what you pass:

  • df.loc['Science'] -> one row as a Series, its values labelled by column names.
  • df.loc[:, 'Arnab'] -> one column as a Series; the colon means “all rows”.
  • df.loc[['Science', 'Hindi']] -> several rows as a DataFrame; the double brackets matter.
  • df.loc[2] -> the row labelled 2. loc always reads an integer as a label, never as a position.

Missing label -> KeyError: every label you ask for must be present in the index (NCERT, p. 59).

Boolean indexing selects by actual values instead of labels (NCERT, p. 50):

  • df.loc['Maths'] > 90 -> a Series of True/False per column, showing where the Maths value exceeds 90.
  • df.loc[:, 'Arnab'] > 90 -> True/False per row, listing the subjects where Arnab scored above 90.
  • df.loc[[True, False, True]] -> a boolean list used as a filter: rows matching True are kept, rows matching False are omitted (NCERT, p. 51).

Label slicing in a DataFrame works like labelled Series slicing — the end label is included (NCERT, p. 51). df.loc['Maths':'Science'] returns both Maths and Science rows. You can combine a row slice with a column selection: df.loc['Maths':'Science', ['Arnab', 'Samridhi']] returns that block of rows with only the listed columns.

Note: one printed output on NCERT p. 50 shows 56 as Arnab’s Maths mark while the same page’s DataFrame holds 90 — treat that as a misprint and always reason from the DataFrame you yourself created.

Joining Two DataFrames with append()

df1.append(df2) stacks the rows of the second DataFrame below the first (NCERT, p. 52). Columns missing from either DataFrame become NaN in the joined result. The chapter teaches this method exactly as it appears here — a row-wise merge of two DataFrames.

Three parameters control the join:

  • sort — sort=True orders the column labels; sort=False keeps the original order of appearance (NCERT, p. 52).
  • ignore_index — True replaces the existing row labels with a fresh 0, 1, 2, … sequence; the default is False (NCERT, p. 53).
  • verify_integrity — True raises an error if the result would contain duplicate row labels; the default False is why the chapter’s example could keep the duplicate label R2.

Original mini example:

import pandas as pd
left = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'], index=['r1', 'r2'])
right = pd.DataFrame([[10, 20]], columns=['B', 'C'], index=['r3'])
joined = left.append(right)
print(joined)
      A     B     C
r1   1.0   2.0   NaN
r2   3.0   4.0   NaN
r3   NaN  10.0  20.0

Column C was absent from left, so its two cells are NaN; column A was absent from right, so r3’s A cell is NaN. The method can also append a single Series or a dictionary to a DataFrame (NCERT, p. 53).

DataFrame Attributes: Shape, Size, dtypes and Transpose

DataFrame attributes mirror the Series attributes, with row and column counts added. The chapter demonstrates them on a slice of the State of Forest Report 2017 (NCERT, p. 53); the values here are fresh but the pattern is identical.

Attribute What it returns
index The row labels as an Index object.
columns The column labels as an Index object.
dtypes The data type of each column.
values A NumPy array of all values, without any axis labels.
shape A tuple (rows, columns) — for a 4-row, 3-column DataFrame, (4, 3).
size The total number of values: rows times columns — for 4 rows and 3 columns, 12.
T The transpose: row labels and column labels swap places.
head(n) First n rows; n defaults to 5.
tail(n) Last n rows; n defaults to 5.
empty True if the DataFrame has no data, else False.

The pair students mix up: shape is a tuple of two numbers (rows, columns), while size is a single integer equal to rows times columns. A 4-row, 3-column DataFrame gives shape (4, 3) and size 12 (NCERT, p. 54).

Transpose: df.T swaps row and column labels. In the chapter’s forest example, the DataFrame’s rows (GeoArea, VeryDense, ModeratelyDense, OpenForest) become columns after transpose, and the states Assam, Kerala, Delhi become the rows (NCERT, p. 55).

CSV Files and DataFrames: read_csv() and to_csv()

A CSV (Comma-Separated Value) file is a plain text file where each line is one record and the values within a line are separated by commas (NCERT, p. 57). Each line is a row; each comma-separated piece is a field — spreadsheet applications open these files directly.

Import with read_csv(): the first argument is the file path. The three parameters to know (NCERT, p. 56):

  • sep — the separator character. The textbook’s note says the default is a space, but current pandas versions default to a comma for read_csv. Since the book and the library can disagree, the safe habit is to always pass sep=',' explicitly rather than rely on any default.
  • header — the row whose values become column names; it also marks where the data starts. header=0 means the first line supplies the column names, and this is the default.
  • names — a list of column labels you supply yourself, instead of taking them from the file.

Export with to_csv(): writes the DataFrame back to disk (NCERT, p. 57). By default both the row labels and the column headers are saved. The parameters control that:

  • path_or_buf — the destination file path (or buffer).
  • sep — the separator, for example sep='@'.
  • header=False — omit the column names.
  • index=False — omit the row labels.

Practical workflow — load, inspect, export (a real report-style task):

import pandas as pd

# 1. Load the marks file
marks = pd.read_csv('C:/NCERT/ResultData.csv', sep=',', header=0)
print(marks)

# 2. Inspect it with DataFrame attributes
print(marks.shape)    # (5, 4) — five rows, four columns
print(marks.size)     # 20
print(marks.dtypes)   # data type of each column
print(marks.head(2))  # first two rows

# 3. Export a cleaned version without the row labels
marks.to_csv('C:/NCERT/ResultData_clean.csv', sep=',', header=True, index=False)

The source file ResultData.csv holds RollNo, Name, Eco and Maths for five students. After loading, shape tells you the table is 5 rows by 4 columns, size confirms 20 values, and the exported file contains the same data without the 0-4 row numbers. You can verify the chapter’s source text in the official NCERT textbook PDF for this chapter.

Pandas Series vs NumPy ndarray: What Changes With Labels

The most important difference: operations between two Series align data automatically by label, so you can write computations without checking whether every Series carries the same labels or the same order (NCERT, p. 57). That automatic alignment is what makes Pandas more flexible than raw arrays for interactive analysis.

Pandas Series NumPy ndarray
You can define your own labelled index — numbers or letters. Elements are accessed by integer position only, starting at 0.
Elements can be indexed in descending order too. The index is fixed from zero; no descending labels.
If two Series are not aligned, NaN (missing values) is generated. There is no concept of NaN; if matching values are absent, alignment fails.
Series require more memory. NumPy occupies less memory.

Pandas also permits non-unique index values — an exception is raised only when you attempt an operation that cannot handle duplicates (NCERT, p. 57). The result of an operation between unaligned Series holds the union of both indexes, with NaN marking any label missing from one side (NCERT, p. 58).

Pandas Syntax Quick Reference: The Patterns to Memorise

Think of this as the chapter’s formula sheet — the patterns you should be able to reproduce without thinking. If you ever need a parameter beyond the chapter’s list, the official pandas documentation is the authoritative reference.

Task Syntax pattern Watch out for
Create a Series from a list pd.Series(data) default index 0 to N-1
Create a Series from an ndarray pd.Series(array, index=labels) index length must match array length, else ValueError
Create a Series from a dictionary pd.Series(dict1) keys become index labels
Access a Series element sr['label'] or sr[2] single label -> one value; list of labels -> Series
Slice a Series sr[1:4]; sr['b':'e'] positional excludes the end; labelled includes it
Add Series with fill_value sr1.add(sr2, fill_value=0) output dtype becomes float64; NaN disappears
Create a DataFrame from a dict of lists pd.DataFrame(dictForest) keys become column labels
Select with loc df.loc['row'], df.loc[:, 'col'], df.loc[['r1', 'r2']] one row/column -> Series; a list -> DataFrame; integers are labels, never positions
Filter with a boolean condition df.loc['Maths'] > 90 gives a True/False Series; df.loc[[True, False, True]] keeps only True rows the condition tests values; the boolean list filters rows by their order
Add a row with loc df.loc['English'] = [85, 86, 83] duplicate label updates the row; wrong length -> ValueError
Drop rows or columns df.drop('Science', axis=0); df.drop('Col', axis=1) axis=0 rows, axis=1 columns
Rename labels df.rename({'Maths': 'Sub1'}, axis='index') axis=’columns’ for column labels; unmapped labels stay unchanged
Append DataFrames df1.append(df2, sort=True, ignore_index=True, verify_integrity=True) sort orders columns; ignore_index resets labels; verify_integrity blocks duplicates
Read a CSV pd.read_csv(path, sep=',', header=0, names=[...]) always pass sep; header=0 means the first line gives column names
Write a CSV df.to_csv(path, sep=',', header=False, index=False) without header=False and index=False, the labels are saved too

Worked Examples: Fresh Data, Full Steps

Two full examples with original numbers. Follow every step — the outputs shown are exactly what Pandas would print.

Worked Example 1: Series alignment — why NaN appears, and how add() with fill_value fills the gaps

Method: index-based alignment, first with the + operator, then with add() and fill_value.

Step 1: define two Series with partly overlapping labels.

import pandas as pd
s1 = pd.Series([2, 4, 6], index=['a', 'b', 'c'])
s2 = pd.Series([10, 20, 30], index=['b', 'c', 'd'])

Only labels b and c exist in both Series; label a exists only in s1 and label d only in s2.

Step 2: operator result with NaN.

print(s1 + s2)
a     NaN
b    14.0
c    26.0
d     NaN
dtype: float64

The output index is the union [a, b, c, d]. Label a has no value in s2, so 2 + missing = NaN; label d has no value in s1, so missing + 30 = NaN. The dtype became float64 because NaN is present.

Step 3: method result with fill_value=0.

print(s1.add(s2, fill_value=0))
a     2.0
b    14.0
c    26.0
d    30.0
dtype: float64

The missing sides are treated as 0 before adding: 2 + 0 = 2.0 and 0 + 30 = 30.0. No NaN remains and every label gets a concrete numeric answer.

Step 4: what changed. The matched pairs (b: 4 + 10 = 14, c: 6 + 20 = 26) are identical in both outputs. Only the unmatched labels changed — from NaN to the fill value. The identical pattern applies to sub(), mul() and div().

Worked Example 2: DataFrame from a dict of lists, loc selection, and boolean filtering

Method: build a DataFrame, select one row with loc, then filter by a score condition and a boolean list.

Step 1: create a small marks DataFrame with original names and numbers.

import pandas as pd
reports = {
    'Student': ['Ayaan', 'Ishita', 'Ronit', 'Zoya'],
    'Maths': [78, 92, 88, 95],
    'Science': [85, 79, 91, 84]
}
df = pd.DataFrame(reports)
print(df)
  Student  Maths  Science
0   Ayaan     78       85
1  Ishita     92       79
2   Ronit     88       91
3    Zoya     95       84

(Marks are unit-free integers, so no unit appears in the output.)

Step 2: select one row with loc.

print(df.loc[2])
Student    Ronit
Maths         88
Science       91
Name: 2, dtype: object

loc[2] returns the row whose label is 2, shown as a Series with the column names as its index.

Step 3: filter by a score condition.

print(df['Maths'] > 88)
0    False
1     True
2    False
3     True
Name: Maths, dtype: bool

The boolean Series flags which students scored above 88 — Ishita and Zoya.

Step 4: use a boolean list to keep only those rows.

print(df.loc[[False, True, False, True]])
  Student  Maths  Science
1  Ishita     92       79
3    Zoya     95       84

Rows 1 and 3 are kept because their positions map to True; rows 0 and 2 are omitted.

Common Mistakes Students Make in Pandas I

Chapter-specific error patterns, with the exact corrections. The third column doubles as a self-check for each error.

Mistake Why it happens Correction (how to check yourself)
Assuming label slicing is end-exclusive You are used to positional slicing from lists and NumPy arrays. sr['b':'e'] includes e. Only positional slices like sr[1:3] stop before the end. Count the output values to confirm.
Thinking loc[2] selects the element at position 2 Position and label look the same on a default index. loc always reads labels. If row labels were strings, df.loc[2] would raise KeyError — that proves it is not positional.
Ignoring NaN after Series arithmetic You forget that alignment happens by label, not position. If NaN appears, either accept it or call s1.add(s2, fill_value=0) to substitute a number. Print the result and check the NaN locations.
Forgetting axis=1 in drop() and deleting the wrong row axis defaults to 0, which means rows. df.drop('Col', axis=1) removes a column; df.drop('Col', axis=0) tries to remove a row with that label. State the axis before you run it.
Confusing DataFrame.shape with DataFrame.size Both words suggest “how big”. shape returns the tuple (rows, columns); size returns rows times columns as one number. For 4 rows and 3 columns: shape (4, 3), size 12.
Adding a row with fewer values than columns Miscounting the number of fields. The list length must match the column count, else ValueError: Cannot set a row with mismatched columns. Count the columns first.
Using a label not in the index with loc Spelling error or a forgotten label. Every label asked for must exist or a KeyError is raised. Inspect df.index and df.columns before calling loc.
Not passing sep or header to read_csv Relying on defaults that the textbook describes loosely. Always pass sep=',' and header=0 explicitly; header=0 means the first line provides the column names.

Exam Notes: Writing Complete Answers

The exercise set on pages 60-62 asks three kinds of work. Match your answer style to the question type.

  • Definitional questions (Q1-Q4): define the structure first (one-dimensional vs two-dimensional), then give the difference — for a Series vs a 1-D array/list/dictionary, talk about labels and flexibility; for a DataFrame vs a 2-D array, talk about column names and mixed dtypes; for size, state whether you mean the number of elements (Series) or the total values (DataFrame).
  • Series exercises (Q5-Q8): questions build a set of named Series (EngAlph, Vowels, Friends, MTseries, MonthDays) and then operate on them. Write the import statement, the constructor call with its data and index, and the expected output — or give the exact one-line statement when asked for a command, such as Vowels[:] = 10 or Vowels3 = Vowels + Vowels1.
  • DataFrame exercises (Q9-Q11): build the Sales DataFrame, then manipulate it. When asked for dimensions, name the tool and state what it returns — shape gives a tuple (rows, columns), size gives the total count. When altering labels, show the output before and after renaming. When writing a CSV, name the function (to_csv()) and the parameters that suppress labels (header=False, index=False).

For the Think and Reflect spots (pp. 30, 41, 46, 48, 49, 53, 57), answer with a reason, not just yes or no. The alias question: pd is a convention — any consistent identifier works. The mismatched-index question: the index length must equal the data length, which is why a ValueError appears. The duplicate-label question: Pandas allows duplicate index values unless the operation cannot handle them.

The missing-value question: NaN marks an absent value, and count() deliberately ignores it.

This is a notes page, so the exercise answers themselves are left for your own practice. What matters is reproducing the right statement pattern every time.

Revision Summary: The Whole Chapter in One Page

The five rules that hold the chapter together:

  1. The default Series index runs from 0 to N-1, where N is the number of elements.
  2. Positional slices exclude the end position; labelled slices include the end label.
  3. Series operations align by index label, and any missing label becomes NaN.
  4. axis=0 means rows and axis=1 means columns — most often in drop().
  5. read_csv() imports a file into a DataFrame; to_csv() exports it back.

Task-to-syntax recap:

Task One-liner
Create a Series pd.Series(data) or pd.Series(dict1)
Add Series with a fill s1.add(s2, fill_value=0)
Create a DataFrame pd.DataFrame({'col': [..]})
Select a row or column df.loc['row'] / df.loc[:, 'col']
Filter rows boolean condition or df.loc[[True, False, True]]
Add a row df.loc['new'] = [..]
Delete rows or columns df.drop('label', axis=0) / axis=1
Append DataFrames df1.append(df2, sort=True)
CSV in / out pd.read_csv(path, sep=',') / df.to_csv(path, index=False)

Series vs DataFrame recap:

Series DataFrame
One-dimensional Two-dimensional
One index: the element labels Two indexes: row labels and column labels
Printed as two columns — index and value Printed as rows and columns
All values share one dtype Each column may have its own dtype
The building block of a DataFrame The structure you export to a CSV file

Takeaway: Pandas gives you labelled, heterogeneous data structures that align by index automatically — which is exactly why it beats raw NumPy arrays for everyday tabular data.

FAQs: Quick Answers to Confusing Pandas Points

What is the difference between a Series and a DataFrame in Pandas?

A Series is one-dimensional: one sequence of values with one set of labels. A DataFrame is two-dimensional: rows and columns, with both a row index and a column index. A DataFrame behaves like a collection of Series sharing the same index, so several Series of different dtypes can sit side by side as columns.

Why do mathematical operations between two Series give NaN for some labels?

Because operations align by index label, not by position. The output index is the union of both indexes, and every label that exists in only one Series has nothing to match with — Pandas fills that side with NaN so the operation completes instead of failing.

Use add(), sub(), mul() or div() with fill_value to replace the missing side with a number.

What is the difference between positional and labelled slicing in a Series?

With positional indices the end position is excluded — sr[1:3] gives positions 1 and 2. With labelled indices the end label is included — sr['b':'e'] gives b, c, d and e. The same rule applies when slicing modifies values: sr[1:3] = 50 changes two positions, while sr['c':'e'] = 500 changes three labels.

How do I load a CSV file into a DataFrame and export it back?

Use pd.read_csv(path, sep=',', header=0) to load, and df.to_csv(path, sep=',', header=False, index=False) to export. header=0 means the first line supplies the column names; header=False and index=False suppress column headers and row labels in the output file.

Does loc[2] in a DataFrame select the value at row position 2?

No — loc always reads an integer as a label, never as a position. In a DataFrame with default labels 0, 1, 2, …, the label 2 coincides with position 2, so the result looks positional. If the row labels are strings, df.loc[2] raises KeyError because no row is labelled 2.

Reference: NCERT Class 12 Informatics Practices textbook, chapter Data Handling Using Pandas – I.

Explore Class 12 Informatics Practices Notes

  • Next: Data Handling using Pandas – II

Related chapters:

  • Plotting Data using Matplotlib notes
  • Internet and Web notes
  • Societal Impacts notes


Official source: download the NCERT textbook free from ncert.nic.in.

Related

More from this section

Plotting Data using Matplotlib Class 12 Notes

These plotting data using matplotlib class 12 notes explain the pyplot workflow, pandas .plot() kinds, customisation, worked examples and common mistakes.

23 min read