💡 Why Inspection & Summary Statistics Matter
When you ingest a new dataset into Pandas, you cannot simply start building AI models or machine learning pipelines blindly. You must first understand the shape of the data, detect missing values, verify data types, and compute descriptive statistics (`mean`, `median`, `percentiles`) to spot anomalies and biases. This module covers the 10 essential inspection techniques every data engineer must master.
1. Quick Inspection with `.head()` and `.tail()`
Viewing the first few or last few rows of a DataFrame to perform a rapid visual sanity check on raw data values.
Python (head_tail_inspect.py)
import pandas as pd
def inspect_head_tail():
data = {'Transaction_ID': [101, 102, 103, 104, 105, 106],
'Amount': [45.50, 120.00, 15.25, 340.00, 89.90, 210.45]}
df = pd.DataFrame(data)
print("--- First 3 Rows (.head(3)) ---")
print(df.head(3))
print("\n--- Last 2 Rows (.tail(2)) ---")
print(df.tail(2))
inspect_head_tail()
Output:
--- First 3 Rows (.head(3)) ---
Transaction_ID Amount
1 45.50
2 120.00
3 15.25
--- Last 2 Rows (.tail(2)) ---
Transaction_ID Amount
5 89.90
6 210.45
2. Structural Audit with `.info()`
Checking total row counts, non-null value counts per column, memory usage, and Pandas data types (`int64`, `float64`, `object`).
Python (dataframe_info.py)
import pandas as pd
import numpy as np
def audit_info():
data = {'Employee': ['Alice', 'Bob', 'Charlie', None],
'Department': ['HR', 'Engineering', 'HR', 'Finance'],
'Salary': [65000, 110000, 72000, 95000]}
df = pd.DataFrame(data)
print("--- DataFrame .info() Summary ---")
df.info()
audit_info()
Output:
--- DataFrame .info() Summary ---
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Employee 3 non-null object
1 Department 4 non-null object
2 Salary 4 non-null int64
dtypes: int64(1), object(2)
memory usage: 224.0+ bytes
3. Comprehensive Statistical Summary with `.describe()`
Generating central tendencies (`mean`, `std`, `min`, `max`, and quartile distributions) for all numeric columns in a single command.
Python (describe_stats.py)
import pandas as pd
def compute_describe():
data = {'Test_Score': [85, 92, 78, 90, 88, 95, 65, 99]}
df = pd.DataFrame(data)
print("--- Statistical Describe ---")
print(df.describe())
compute_describe()
Output:
--- Statistical Describe ---
Test_Score
count 8.000000
mean 86.500000
std 10.515259
min 65.000000
25% 83.250000
50% 89.000000
75% 92.750000
max 99.000000
4. Dimension Attributes: `.shape`, `.axes`, and `.dtypes`
Extracting structural dimensions and data types programmatically for data pipeline validation checks.
Python (dimensions_check.py)
import pandas as pd
def check_dimensions():
data = {'Product': ['Laptop', 'Mouse', 'Keyboard'],
'Price': [1200.0, 25.5, 75.0],
'In_Stock': [True, True, False]}
df = pd.DataFrame(data)
print(f"Shape (Rows, Cols): {df.shape}")
print(f"Total Elements: {df.size}")
print("\nColumn Data Types:")
print(df.dtypes)
check_dimensions()
Output:
Shape (Rows, Cols): (3, 3)
Total Elements: 9
Column Data Types:
Product object
Price float64
In_Stock bool
dtype: object
5. Frequency Counting with `.value_counts()`
Counting the occurrence frequency of categorical variables to uncover distribution imbalances.
Python (value_counts_demo.py)
import pandas as pd
def analyze_frequencies():
data = {'City': ['New York', 'London', 'Paris', 'New York', 'London', 'New York', 'Tokyo']}
df = pd.DataFrame(data)
counts = df['City'].value_counts()
print("--- City Frequency Count ---")
print(counts)
analyze_frequencies()
Output:
--- City Frequency Count ---
New York 3
London 2
Paris 1
Tokyo 1
Name: City, dtype: int64
6. Checking for Missing Values with `.isnull().sum()`
Auditing datasets for missing data (`NaN`, `None`) across every column to plan data cleaning strategies.
Python (missing_audit.py)
import pandas as pd
import numpy as np
def audit_missing():
data = {'Customer': ['Alice', 'Bob', None, 'David'],
'Age': [25, np.nan, 35, 42],
'Email': ['a@mail.com', None, None, 'd@mail.com']}
df = pd.DataFrame(data)
missing_summary = df.isnull().sum()
print("--- Missing Values Per Column ---")
print(missing_summary)
audit_missing()
Output:
--- Missing Values Per Column ---
Customer 1
Age 1
Email 2
dtype: int64
7. Unique Values and Cardinality Check (`.unique()`, `.nunique()`)
Inspecting distinct categories in a column and measuring feature cardinality before machine learning encoding.
Python (cardinality_check.py)
import pandas as pd
def check_cardinality():
data = {'Category': ['Electronics', 'Clothing', 'Electronics', 'Home', 'Clothing', 'Electronics']}
df = pd.DataFrame(data)
print(f"Unique Categories: {df['Category'].unique()}")
print(f"Total Unique Count: {df['Category'].nunique()}")
check_cardinality()
Output:
Unique Categories: ['Electronics' 'Clothing' 'Home']
Total Unique Count: 3
8. Custom Percentile & Quantile Extraction (`.quantile()`)
Extracting precise statistical thresholds like the 90th or 95th percentile for financial risk modeling or outlier removal.
Python (quantile_analysis.py)
import pandas as pd
def compute_quantiles():
data = {'House_Price': [150000, 200000, 250000, 300000, 450000, 1200000]}
df = pd.DataFrame(data)
p50 = df['House_Price'].quantile(0.50) # Median
p90 = df['House_Price'].quantile(0.90) # 90th percentile
print(f"50th Percentile (Median): ${p50:,.2f}")
print(f"90th Percentile: ${p90:,.2f}")
compute_quantiles()
Output:
50th Percentile (Median): $275,000.00
90th Percentile: $795,000.00
9. Correlation Matrix Inspection (`.corr()`)
Calculating Pearson correlation coefficients between numerical columns to identify linear relationships.
Python (correlation_matrix.py)
import pandas as pd
def compute_correlation():
data = {'Study_Hours': [2, 4, 6, 8, 10],
'Exam_Score': [50, 65, 80, 90, 98],
'Sleep_Hours': [8, 7, 7, 6, 6]}
df = pd.DataFrame(data)
corr_matrix = df.corr()
print("--- Correlation Matrix ---")
print(corr_matrix)
compute_correlation()
Output:
--- Correlation Matrix ---
Study_Hours Exam_Score Sleep_Hours
Study_Hours 1.000000 0.992683 -0.948683
Exam_Score 0.992683 1.000000 -0.957826
Sleep_Hours -0.948683 -0.957826 1.000000
10. Individual Statistical Methods (`.mean()`, `.median()`, `.std()`, `.sum()`)
Executing targeted statistical queries on specific DataFrame columns instead of calling the full `.describe()` suite.
Python (targeted_stats.py)
import pandas as pd
def targeted_aggregations():
data = {'Daily_Revenue': [1200, 1450, 1100, 1600, 2100, 1900]}
df = pd.DataFrame(data)
print(f"Total Cumulative Revenue: ${df['Daily_Revenue'].sum():,}")
print(f"Mean Daily Revenue: ${df['Daily_Revenue'].mean():,.2f}")
print(f"Standard Deviation: ${df['Daily_Revenue'].std():,.2f}")
targeted_aggregations()
Output:
Total Cumulative Revenue: $9,350
Mean Daily Revenue: $1,558.33
Standard Deviation: $375.46