# Module 6: Data Inspection ## Learning Objectives By the end of this module, you will be able to: - Use `head()`, `tail()`, and `sample()` to preview data - Generate summary statistics with `describe()` and `info()` - Inspect DataFrame shape, column data types, and memory usage - Detect missing values using multiple strategies --- ## Previewing Data Before any analysis, you need to understand what your data looks like. ### `head()` — First N rows ```python import pandas as pd df = pd.read_csv("data/sales.csv") # First 5 rows (default) print(df.head()) # First 10 rows print(df.head(10)) ``` ### `tail()` — Last N rows ```python # Last 5 rows print(df.tail()) # Last 3 rows print(df.tail(3)) ``` ### `sample()` — Random rows ```python # 5 random rows print(df.sample(5)) # Random 10% of the dataset print(df.sample(frac=0.1)) # With a random seed for reproducibility print(df.sample(5, random_state=42)) ``` ```{tip} Use `sample()` to quickly inspect large datasets without bias. Setting `random_state` ensures you get the same rows every time. ``` ## Shape and Structure ### `shape` — Dimensions ```python print(df.shape) # (rows, columns) print(f"Rows: {df.shape[0]}, Columns: {df.shape[1]}") ``` ### `columns` and `index` ```python print(df.columns) # All column names print(df.index) # Row index print(len(df.columns)) # Number of columns print(len(df)) # Number of rows ``` ## Data Types ### `dtypes` — Column data types ```python print(df.dtypes) ``` **Output (example):** ``` Name object Age int64 Salary float64 DOB object dtype: object ``` ### Checking and converting types ```python # Check individual column print(df["Age"].dtype) # int64 # Count types print(df.dtypes.value_counts()) # Convert types df["Age"] = df["Age"].astype(float) df["DOB"] = pd.to_datetime(df["DOB"]) ``` ```{note} Common Pandas dtypes: `int64`, `float64`, `object` (strings/mixed), `bool`, `datetime64[ns]`, `category`. ``` ## Summary Information ### `info()` — Concise DataFrame summary ```python df.info() ``` **Output:** ``` RangeIndex: 1000 entries, 0 to 999 Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Name 1000 non-null object 1 Age 950 non-null float64 2 Salary 900 non-null float64 3 DOB 950 non-null object 4 City 1000 non-null object dtypes: float64(2), object(3) memory usage: 39.2+ KB ``` ```{tip} The `Non-Null Count` column in `info()` immediately reveals which columns have missing values. This is your first clue for data cleaning. ``` ### `describe()` — Summary statistics ```python # Numeric columns only print(df.describe()) # All columns (including categorical) print(df.describe(include="all")) # Specific percentiles print(df.describe(percentiles=[0.05, 0.25, 0.5, 0.75, 0.95])) # Categorical columns print(df.describe(include=["object"])) ``` **Output:** ``` Age Salary count 950.000000 900.000000 mean 34.526316 65000.000000 std 10.123456 15000.000000 min 18.000000 30000.000000 25% 25.000000 52000.000000 50% 33.000000 62000.000000 75% 42.000000 75000.000000 max 65.000000 120000.000000 ``` ## Memory Usage ```python # Memory usage of entire DataFrame print(df.memory_usage()) # Deep memory usage (includes object dtype contents) print(df.memory_usage(deep=True)) # Total memory print(df.memory_usage(deep=True).sum()) # Per column memory in a readable format print(df.memory_usage(deep=True).apply(lambda x: f"{x / 1024:.2f} KB")) ``` ```{warning} The `deep=True` parameter is necessary to accurately measure memory for columns with `object` dtype, which stores Python objects (strings etc.) that are not counted by default. ``` ## Detecting Missing Values ```python # Count missing values per column print(df.isna().sum()) # Percentage of missing values print(df.isna().mean() * 100) # Total missing values in the DataFrame print(df.isna().sum().sum()) # Rows with any missing value print(df[df.isna().any(axis=1)]) # Columns with missing values print(df.columns[df.isna().any()].tolist()) # Heatmap visualisation of missing values import matplotlib.pyplot as plt import seaborn as sns plt.figure(figsize=(10, 6)) sns.heatmap(df.isna(), cbar=False, yticklabels=False) plt.title("Missing Values Heatmap") plt.show() ``` ### Comparing `isna()` vs `isnull()` ```python # These are identical — both check for missing values print(df.isna().sum() == df.isnull().sum()) # True ``` ```{note} `isna()` and `isnull()` are aliases. Use whichever reads better in context — both are equally valid. ``` ## Verifying Uniqueness ```python # Unique values per column for col in df.columns: print(f"{col}: {df[col].nunique()} unique values") # Duplicate rows print(f"Duplicate rows: {df.duplicated().sum()}") # View duplicate rows print(df[df.duplicated(keep=False)]) ``` ## Value Counts ```python # Frequency counts for categorical columns print(df["Department"].value_counts()) # Normalised (relative frequencies) print(df["Department"].value_counts(normalize=True) * 100) # Top 5 most common values print(df["City"].value_counts().head(5)) ``` ## Comprehensive Inspection Function ```python def inspect_dataframe(df): """Print a comprehensive summary of a DataFrame.""" print(f"{'='*60}") print(f"Shape: {df.shape}") print(f"{'='*60}") print("\n--- First 3 rows ---") print(df.head(3)) print("\n--- Data Types ---") print(df.dtypes) print("\n--- Summary Statistics ---") print(df.describe(include="all")) print("\n--- Missing Values ---") missing = pd.DataFrame({ "Missing": df.isna().sum(), "Percent": (df.isna().mean() * 100).round(2), }) print(missing[missing["Missing"] > 0]) print("\n--- Memory Usage ---") print(f"Total: {df.memory_usage(deep=True).sum() / 1024:.2f} KB") print(f"{'='*60}") inspect_dataframe(df) ``` ## Summary - `head()`, `tail()`, and `sample()` are essential for quick previews - `shape`, `info()`, and `describe()` reveal the DataFrame's structure and distributions - `dtypes` shows column types; `memory_usage(deep=True)` shows real memory cost - `isna().sum()` quantifies missing data per column - `value_counts()` and `nunique()` are vital for categorical exploration ## Exercises Using the dataset: ```python import pandas as pd import numpy as np df = pd.DataFrame({ "ID": range(1, 101), "Name": [f"Person_{i}" for i in range(1, 101)], "Age": np.random.randint(18, 70, 100).astype(float), "Salary": np.random.normal(60000, 15000, 100), "Department": np.random.choice(["HR", "IT", "Sales", "Marketing"], 100), "Join_Date": pd.date_range("2020-01-01", periods=100, freq="D"), }) # Introduce some missing values df.loc[10:15, "Age"] = np.nan df.loc[30:35, "Salary"] = np.nan df.loc[50, "Department"] = np.nan ``` 1. Print the first 8 rows and the last 2 rows 2. Use `info()` to find which columns have null values 3. Use `describe()` with custom percentiles and compare the 25th and 75th percentiles 4. Create a heatmap of missing values using `seaborn` 5. Write a function that returns the columns with more than 5% missing data ## Further Reading - [Pandas DataFrame Inspection](https://pandas.pydata.org/docs/user_guide/basics.html) - [Visualising Missing Data with Missingno](https://github.com/ResidentMario/missingno)