Circle of Learning Logo CIRCLE OF LEARNING Excellence in Education
CBSE Class 12 · Informatics Practices Chapter 2 Session 2026-27

Data Handling using Pandas - II Formulas & Cheat Sheet

Complete chapter-wise reference, step-by-step formula explanations, structured table, and board exam trap warnings.

Core Concepts & Theoretical Foundations

  • Descriptive Statistics: `max()`, `min()`, `count()`, `sum()`, `mean()`, `median()`, `mode()`, `std()`, `var()`, `quantile()`.
  • Aggregation Axis: By default, statistical functions in DataFrame operate vertically across rows for each column (`axis=0` or `axis='index'`). Setting `axis=1` or `axis='columns'` calculates statistics horizontally across columns for each row.
  • Handling Missing Data (NaN): `isna()` or `isnull()` detects missing values; `notna()` or `notnull()` detects non-missing values.
  • Dropping Missing Data: `df.dropna(axis=0/1, how='any'/'all')` removes rows or columns containing missing values.
  • Imputing Missing Data: `df.fillna(value)` substitutes missing values with a designated constant, mean, or median.
  • Sorting Data: `df.sort_values(by=col_name, ascending=True/False)` sorts rows based on values; `df.sort_index(ascending=True/False)` sorts rows/columns by labels.
  • CSV File I/O: `pd.read_csv('filename.csv')` imports tabular CSV into DataFrame; `df.to_csv('filename.csv', index=False)` writes DataFrame to CSV file.

Chapter Formulas & Equations (12 entries)

# Topic / Formula Name Mathematical Form & Equation Conditions, Meaning & Board Tips
1 Arithmetic Mean Formula across Column / Row
xˉj=∑i=1njxi,jnj,nj=count of valid non-NaN entries\bar{x}_j = \frac{\sum_{i=1}^{n_j} x_{i, j}}{n_j}, \quad n_j = \text{count of valid non-NaN entries}

Computes arithmetic mean per column (axis=0) or per row (axis=1), automatically excluding missing NaN cells.

2 Sample Standard Deviation Formula
s=1N−1∑i=1N(xi−xˉ)2s = \sqrt{\frac{1}{N - 1} \sum_{i=1}^N (x_i - \bar{x})^2}

Measures dispersion of numeric data points around the mean. Uses Bessel's correction (ddof=1) by default.

3 Variance Relation
Var(X)=s2=1N−1∑i=1N(xi−xˉ)2\text{Var}(X) = s^2 = \frac{1}{N - 1} \sum_{i=1}^N (x_i - \bar{x})^2

The variance is the square of standard deviation representing average squared deviation.

4 Missing Value Detection Function
isna(x)={Trueif x=NaN / NoneFalseotherwise\text{isna}(x) = \begin{cases} \text{True} & \text{if } x = \text{NaN / None} \\ \text{False} & \text{otherwise} \end{cases}

Flags missing entries as True. Use `df.isna().sum()` to obtain column-wise count of missing cells.

5 Dropping Missing Values Syntax
dropna(axis=0,how=’any’∣’all’)\text{dropna}(\text{axis}=0, \text{how}=\text{'any'}|\text{'all'})

Removes rows (axis=0) or columns (axis=1) if any value is missing ('any') or all values are missing ('all').

6 Missing Value Imputation Syntax
xi,j←fill_val∀  (i,j) where xi,j=NaNx_{i, j} \leftarrow \text{fill\_val} \quad \forall \; (i, j) \text{ where } x_{i, j} = \text{NaN}

Replaces missing NaN values with specified constant or computed statistics (e.g. mean or median).

7 Sorting Values Syntax
sort_values(by=’Col’,ascending=True∣False)\text{sort\_values}(by=\text{'Col'}, \text{ascending}=\text{True}|\text{False})

Sorts records along rows by specified column values in ascending or descending sequence.

8 Sorting by Index Labels Syntax
sort_index(axis=0∨1,ascending=True∣False)\text{sort\_index}(\text{axis}=0 \lor 1, \text{ascending}=\text{True}|\text{False})

Sorts rows (axis=0) or column labels (axis=1) alphabetically or numerically by index label.

9 Reading Data from CSV File
df=pd.read_csv(filepath,sep=’,’)\text{df} = \text{pd.read\_csv}(\text{filepath}, \text{sep}=\text{','})

Parses comma-separated text file into 2D DataFrame with automatic header inference.

10 Exporting DataFrame to CSV File
df.to_csv(filepath,index=False)\text{df.to\_csv}(\text{filepath}, \text{index}=\text{False})

Serializes DataFrame into CSV format on disk; setting index=False suppresses saving the numeric row index.

11 Quantile Computation
Q(q)=value at percentile rank q∈[0,1]Q(q) = \text{value at percentile rank } q \in [0, 1]

Finds value below which a given percentage of observations in a group of observations falls.

12 Count Function Excluding NaN
countj=Ntotal−NNaN\text{count}_j = N_{\text{total}} - N_{\text{NaN}}

Unlike len(df) which counts total rows, count() ignores missing values.

Key Scientific Diagrams & Concept Schematics: Data Handling using Pandas - II

Visual Reference: pandas-aggregation-pipeline

Official NCERT board curriculum concept schematic and mathematical/scientific reference diagram.

Step-by-Step Worked Board Exam Examples

Example 1: A DataFrame 'Marks' has columns ['Roll', 'Score'] with Score values [85, NaN, 90, NaN, 75]. Write commands to: (a) display total missing scores, and (b) fill missing scores with average score.

Step 1: To count missing scores, use Marks['Score'].isna().sum().

Step 2: To calculate the average score excluding NaNs: avg_score = Marks['Score'].mean().

Step 3: Fill missing scores: Marks['Score'].fillna(avg_score, inplace=True).

Ans: (a) print(Marks['Score'].isna().sum()) # Output: 2 (b) Marks['Score'].fillna(Marks['Score'].mean(), inplace=True)

Example 2: Given a DataFrame 'Emp' with columns ['EmpId', 'Name', 'Salary'], write statements to: (a) sort employees by Salary in descending order, and (b) save the sorted DataFrame to 'high_salary.csv' without index.

Step 1: Sort by Salary descending: sorted_emp = Emp.sort_values(by='Salary', ascending=False).

Step 2: Export to CSV without row numbers: sorted_emp.to_csv('high_salary.csv', index=False).

Ans: sorted_emp = Emp.sort_values(by='Salary', ascending=False) sorted_emp.to_csv('high_salary.csv', index=False)

Common Mistakes to Avoid in Exam

  • Confusing `df.count()` with `len(df)`: `len(df)` returns total row count including NaNs, whereas `df.count()` ignores NaNs.
  • Setting `axis=0` thinking it operates horizontally: in Pandas, `axis=0` operates down columns across rows, while `axis=1` operates across columns for each row.
  • Forgetting `index=False` when calling `to_csv()`, creating an unwanted unnamed column for index labels in the generated CSV file.
  • Using `== np.nan` to detect missing values instead of `isna()`: in Python/IEEE 754, `np.nan == np.nan` evaluates to False.

Target Practice Questions

Q1. Write code to read a CSV file 'sales.csv' and find the maximum sales in column 'Amount'.

Correct Answer: import pandas as pd df = pd.read_csv('sales.csv') print(df['Amount'].max())

Q2. What is the purpose of the 'subset' parameter in df.dropna()?

Correct Answer: It restricts the missing-value check to specific columns or rows instead of inspecting the whole DataFrame.

Q3. How can you sort a DataFrame 'df' by column 'Age' ascending and 'Salary' descending?

Correct Answer: df.sort_values(by=['Age', 'Salary'], ascending=[True, False], inplace=True)

Frequently Asked Questions

Q. What is the default value of axis in DataFrame statistical functions?

The default is axis=0 (or axis='index'), which calculates the statistical metric column-wise across all rows.

Q. How does fillna(method='pad') or fillna(method='bfill') work?

Forward fill ('pad'/'ffill') replaces NaN with the previous valid observation, while backward fill ('bfill') propagates the next valid observation backwards.

Q. Why does np.nan == np.nan return False?

By IEEE floating-point standard, NaN is defined as not equal to any value, including itself. You must use `pd.isna()` or `np.isnan()` for comparison.

Q. What is the difference between how='any' and how='all' in dropna()?

how='any' drops the row/column if even one single element is NaN; how='all' drops the row/column only if every single element in that row/column is NaN.

← View All 6 Chapters in Class 12 Informatics Practices Formula Book