# Module 7: Data Cleaning ## Learning Objectives By the end of this module, you will be able to: - Handle missing values through removal, imputation, and interpolation - Identify and remove duplicate rows - Clean and standardise string data - Rename columns and replace values - Convert data types safely - Detect and remove outliers --- ```{warning} Data cleaning typically consumes 60–80% of the total time in a data science project. Investing in robust cleaning pipelines pays enormous dividends downstream. ``` ## Handling Missing Values ### Detecting missing values ```python import pandas as pd import numpy as np df = pd.read_csv("data/messy_data.csv") # Count missing values print(df.isna().sum()) print(f"Total missing: {df.isna().sum().sum()}") ``` ### Removing missing values ```python # Drop rows with any missing value df_clean = df.dropna() # Drop rows where ALL values are missing df_clean = df.dropna(how="all") # Drop rows with missing values in specific columns df_clean = df.dropna(subset=["Age", "Salary"]) # Drop columns below a completeness threshold threshold = len(df) * 0.6 # Keep columns with ≥ 60% non-null df_clean = df.dropna(thresh=threshold, axis=1) ``` ```{note} Be cautious with `dropna()`. Removing rows reduces sample size and can introduce bias if missingness is not random. ``` ### Filling missing values ```python # Fill with a constant df["Age"] = df["Age"].fillna(0) # Fill with column mean / median / mode df["Age"] = df["Age"].fillna(df["Age"].mean()) df["Salary"] = df["Salary"].fillna(df["Salary"].median()) df["Department"] = df["Department"].fillna(df["Department"].mode()[0]) # Forward fill (carry last value forward) df["Sales"] = df["Sales"].fillna(method="ffill") # Backward fill df["Sales"] = df["Sales"].fillna(method="bfill") # Fill with a grouped statistic df["Salary"] = df.groupby("Department")["Salary"].transform( lambda x: x.fillna(x.median()) ) ``` ```{tip} For time series data, forward fill (`ffill`) is often more appropriate than using the mean, because it preserves temporal continuity. ``` ### Interpolation ```python # Linear interpolation df["Temperature"] = df["Temperature"].interpolate(method="linear") # Time-based interpolation df["Value"] = df["Value"].interpolate(method="time") # Polynomial interpolation df["Value"] = df["Value"].interpolate(method="polynomial", order=2) ``` ## Handling Duplicates ```python # Check for duplicates print(f"Duplicate rows: {df.duplicated().sum()}") # View duplicate rows (keep=False shows all occurrences) print(df[df.duplicated(keep=False)]) # Drop duplicates (keeps first occurrence by default) df_clean = df.drop_duplicates() # Drop duplicates based on specific columns df_clean = df.drop_duplicates(subset=["Name", "Email"]) # Keep the last occurrence instead df_clean = df.drop_duplicates(keep="last") # Reset index after dropping df_clean = df.drop_duplicates().reset_index(drop=True) ``` ## String Cleaning ```python # Strip whitespace df["Name"] = df["Name"].str.strip() # Convert case df["Name"] = df["Name"].str.upper() df["Name"] = df["Name"].str.lower() df["Name"] = df["Name"].str.title() # Replace substrings df["Phone"] = df["Phone"].str.replace(r"[^0-9]", "", regex=True) # Check for patterns mask = df["Email"].str.contains(r"@.+\.com", regex=True, na=False) # Split strings df[["First", "Last"]] = df["Full_Name"].str.split(" ", n=1, expand=True) # Extract patterns df["Domain"] = df["Email"].str.extract(r"@(.+)") # Pad strings df["ID"] = df["ID"].astype(str).str.zfill(6) # Remove leading zeros df["Code"] = df["Code"].str.lstrip("0") ``` ```{warning} Most string methods have `na=False` parameter. Always specify it to avoid propagating NaN values unintentionally. ``` ### Commonly needed string operations ```python # Unified whitespace treatment def clean_text(text): """Normalise whitespace in a string.""" if pd.isna(text): return text return " ".join(text.split()) df["Description"] = df["Description"].apply(clean_text) # Remove special characters df["Clean_Text"] = df["Raw_Text"].str.replace(r"[^\w\s]", "", regex=True) # Remove multiple spaces df["Clean_Text"] = df["Raw_Text"].str.replace(r"\s+", " ", regex=True) ``` ## Renaming Columns ```python # Rename specific columns df = df.rename(columns={ "old_name": "new_name", "Full_Name": "FullName", }) # Rename using a function (e.g., lowercase, strip) df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_") # Using a mapping function def clean_column_name(col: str) -> str: """Convert column name to snake_case.""" return col.strip().lower().replace(" ", "_").replace("-", "_") df.columns = [clean_column_name(c) for c in df.columns] ``` ```{tip} Storing column names in `snake_case` is the Pandas convention and avoids issues with query syntax that requires spaces to be quoted. ``` ## Replacing Values ```python # Replace specific values df["Gender"] = df["Gender"].replace({"M": "Male", "F": "Female", np.nan: "Unknown"}) # Replace across multiple columns df = df.replace({"?": np.nan, "N/A": np.nan, "NULL": np.nan}) # With regex df["Price"] = df["Price"].str.replace(r"[\$,]", "", regex=True).astype(float) # Conditional replacement df.loc[df["Age"] < 0, "Age"] = np.nan ``` ## Converting Data Types ```python # Explicit conversion df["Age"] = df["Age"].astype(int) df["Price"] = df["Price"].astype(float) # Safe numeric conversion (coerce errors to NaN) df["Salary"] = pd.to_numeric(df["Salary"], errors="coerce") # Date conversion df["Date"] = pd.to_datetime(df["Date"], errors="coerce") # Categorical dtype (saves memory) df["Department"] = df["Department"].astype("category") # Boolean conversion df["Is_Active"] = df["Status"].map({"Active": True, "Inactive": False}) ``` ```{note} Use `pd.to_numeric()` with `errors="coerce"` instead of `.astype(float)` when you suspect non-numeric values in the column — it converts problematic entries to NaN rather than raising an error. ``` ## Outlier Removal ```python # Z-score method from scipy import stats z_scores = np.abs(stats.zscore(df["Salary"].dropna())) df_clean = df[(z_scores < 3) | (df["Salary"].isna())] # IQR method Q1 = df["Salary"].quantile(0.25) Q3 = df["Salary"].quantile(0.75) IQR = Q3 - Q1 lower_bound = Q1 - 1.5 * IQR upper_bound = Q3 + 1.5 * IQR df_clean = df[(df["Salary"] >= lower_bound) & (df["Salary"] <= upper_bound)] # Percentile clipping df["Salary"] = df["Salary"].clip( lower=df["Salary"].quantile(0.01), upper=df["Salary"].quantile(0.99), ) # Visual inspection import matplotlib.pyplot as plt df.boxplot(column="Salary") plt.title("Salary Distribution (Outlier Detection)") plt.show() ``` ```{tip} Outlier removal should always be justified by domain knowledge. Consider winsorizing (clipping) outliers instead of removing them to preserve sample size. ``` ## Complete Cleaning Pipeline ```python def clean_dataset(df): """Apply a standard cleaning pipeline to a DataFrame.""" df = df.copy() # Standardise column names df.columns = ( df.columns .str.strip() .str.lower() .str.replace(r"[^a-z0-9_]", "_", regex=True) .str.replace(r"_+", "_", regex=True) ) # Remove fully empty rows and columns df = df.dropna(how="all").dropna(axis=1, how="all") # Remove duplicates df = df.drop_duplicates().reset_index(drop=True) # Replace common missing value indicators df = df.replace({"?": np.nan, "N/A": np.nan, "NULL": np.nan, "": np.nan}) # Convert date columns date_cols = df.select_dtypes(include=["object"]).columns for col in date_cols: try: df[col] = pd.to_datetime(df[col], errors="raise") except (ValueError, TypeError): pass # Strip whitespace from string columns str_cols = df.select_dtypes(include=["object"]).columns for col in str_cols: df[col] = df[col].str.strip() return df df_clean = clean_dataset(df) ``` ## Summary - Handle missing values with `dropna()`, `fillna()`, or `interpolate()` - Remove duplicates with `drop_duplicates()` - Clean strings using the `.str` accessor methods - Rename columns for consistency and readability - Replace values using dictionaries or regex patterns - Convert types safely with `pd.to_numeric()` and `pd.to_datetime()` - Detect outliers using Z-score or IQR methods - Build reusable cleaning pipelines for consistency ## Exercises Using this dataset: ```python import pandas as pd import numpy as np df = pd.DataFrame({ " Full Name ": [" Alice ", "Bob", "CHARLIE", "diana ", None, "Bob", " eve "], " age(years)": [30, None, -5, 25, 40, 30, "unknown"], " SALARY ": [50000, 60000, "$70,000", None, "55,000", 60000, "N/A"], "Dept": [" HR ", "IT", "HR", "IT", " HR ", "IT", "SALES"], }) ``` 1. Strip whitespace from all string columns and rename them to snake_case 2. Replace negative ages with NaN and convert the age column to numeric 3. Remove the `$` and `,` from the salary column and convert to float 4. Replace "N/A" and "unknown" with NaN, impute numeric columns with their median 5. Remove duplicate rows, keeping the first occurrence 6. Remove outliers from the salary column using the IQR method ## Further Reading - [Pandas Working with Missing Data](https://pandas.pydata.org/docs/user_guide/missing_data.html) - [Pandas Text Data](https://pandas.pydata.org/docs/user_guide/text.html) - [Outlier Detection Techniques](https://scikit-learn.org/stable/modules/outlier_detection.html)