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 |
|
Computes arithmetic mean per column (axis=0) or per row (axis=1), automatically excluding missing NaN cells. |
| 2 | Sample Standard Deviation Formula |
|
Measures dispersion of numeric data points around the mean. Uses Bessel's correction (ddof=1) by default. |
| 3 | Variance Relation |
|
The variance is the square of standard deviation representing average squared deviation. |
| 4 | Missing Value Detection Function |
|
Flags missing entries as True. Use `df.isna().sum()` to obtain column-wise count of missing cells. |
| 5 | Dropping Missing Values Syntax |
|
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 |
|
Replaces missing NaN values with specified constant or computed statistics (e.g. mean or median). |
| 7 | Sorting Values Syntax |
|
Sorts records along rows by specified column values in ascending or descending sequence. |
| 8 | Sorting by Index Labels Syntax |
|
Sorts rows (axis=0) or column labels (axis=1) alphabetically or numerically by index label. |
| 9 | Reading Data from CSV File |
|
Parses comma-separated text file into 2D DataFrame with automatic header inference. |
| 10 | Exporting DataFrame to CSV File |
|
Serializes DataFrame into CSV format on disk; setting index=False suppresses saving the numeric row index. |
| 11 | Quantile Computation |
|
Finds value below which a given percentage of observations in a group of observations falls. |
| 12 | Count Function Excluding 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).
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).
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.