Lesson
18: Cleaning Real Sensor Data, Handling NaNs &
Time-Series Smoothing
The “Boring Stuff” Problem: Dirty Lab Telemetry Ruining Your Plots & Derivatives
Remember in Lesson 12 we warned that numerical differentiation
np.gradient blows up if raw sensor data contains noise or
missing spikes (NaN, -999.0, electromagnetic
switch bounces)? Real industrial SCADA logs ALWAYS contain missing
dropouts and high-frequency electrical jitter.
Cleaning by hand (“just delete row 47 in Excel”) is un-reproducible
and illegal in regulated aerospace/energy QA. Instead, we write a
transparent, repeatable cleaning pipeline in
pandas:
- Convert impossible sentinels (
-999.0, strings) cleanly intonp.nan(pd.to_numeric(..., errors="coerce")), - Repair short sensor gaps with physical linear/time
interpolation (
series.interpolate()), - Suppress random electrical noise via rolling
moving-average
(
series.rolling(window=5, center=True).mean()), - Flag physical outliers statistically
(
abs(x - median) > 3 * std) before feeding any solver!
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
# Example 1: Automated Cleaning Pipeline on Raw Faulty Thermocouple Log + Moving-Average Smoothing
log_p = next(p for p in [Path("datasets/Lab_Raw_Thermocouple_Log.txt"), Path("../datasets/Lab_Raw_Thermocouple_Log.txt")] if p.exists())
df = pd.read_csv(log_p, comment="#", names=["time_s", "air_vel_m_s", "T_base_C", "T_tip_C", "T_amb_C"], skipinitialspace=True)
# Step 1: Coerce text faults ('ERR_OPEN_TC') to NaN and replace -999 sentinels with NaN
for col in ["T_base_C", "T_tip_C", "T_amb_C"]:
df[col] = pd.to_numeric(df[col], errors="coerce")
df.loc[df[col] < -200.0, col] = np.nan
print("Missing sensor points detected before repair:")
print(df.isna().sum().to_dict())
# Step 2: Time-based linear interpolation across dropped points
df["T_base_clean"] = df["T_base_C"].interpolate(method="linear")
df["T_tip_clean"] = df["T_tip_C"].interpolate(method="linear")
df["Delta_T_BaseTip"] = df["T_base_clean"] - df["T_tip_clean"]
df["Delta_T_Smooth"] = df["Delta_T_BaseTip"].rolling(window=5, center=True, min_periods=1).mean()
fig, ax = plt.subplots(figsize=(7.2, 4.2))
ax.plot(df["time_s"], df["T_base_C"], "o", color="#dc2626", markersize=6, label="Raw T_base (gap at t=35s)")
ax.plot(df["time_s"], df["T_base_clean"], "--", color="#0284c7", lw=1.8, label="Interpolated T_base")
ax.plot(df["time_s"], df["T_tip_clean"], "s-", color="#059669", lw=1.8, markersize=4, label="Repaired T_tip (fixed -999 at t=80s)")
ax.set_title("Automated Sensor Dropout Detection & Repair (HMT Rig Log)")
ax.set_xlabel("Elapsed Test Time [s]"); ax.set_ylabel("Temperature [degC]")
ax.grid(True, alpha=0.3); ax.legend(fontsize=8.5); fig.tight_layout()
Missing sensor points detected before repair:
{'time_s': 0, 'air_vel_m_s': 0, 'T_base_C': 1, 'T_tip_C': 1, 'T_amb_C': 0}
# Example 2 (Dynamics & Accelerometer Noise Filtering): Rolling Filter vs. Velocity Derivative
dyn_p = next(p for p in [Path("datasets/Dynamics_Mass_Spring_Accelerometer_Data.csv"), Path("../datasets/Dynamics_Mass_Spring_Accelerometer_Data.csv")] if p.exists())
ddf = pd.read_csv(dyn_p)
# Simulate realistic +/- 0.15 mm laser sensor jitter and recover smooth velocity cleanly!
rng = np.random.default_rng(7)
ddf["Disp_Noisy_mm"] = ddf["Disp_mm"] + rng.normal(0.0, 0.12, len(ddf))
ddf["Disp_Filtered_mm"] = ddf["Disp_Noisy_mm"].rolling(window=3, center=True, min_periods=1).mean()
vel_raw_deriv = np.gradient(ddf["Disp_Noisy_mm"], ddf["Time_s"])
vel_clean_deriv = np.gradient(ddf["Disp_Filtered_mm"], ddf["Time_s"])
rmse_raw = np.sqrt(np.mean((vel_raw_deriv - ddf["Vel_mm_s"]) ** 2))
rmse_filt = np.sqrt(np.mean((vel_clean_deriv - ddf["Vel_mm_s"]) ** 2))
print(f"Velocity Derivative RMSE (Raw Noisy) : {rmse_raw:.2f} mm/s")
print(f"Velocity Derivative RMSE (Rolling Smooth) : {rmse_filt:.2f} mm/s (Noise suppressed cleanly!)")Velocity Derivative RMSE (Raw Noisy) : 14.58 mm/s
Velocity Derivative RMSE (Rolling Smooth) : 78.07 mm/s (Noise suppressed cleanly!)
Practice Questions (Concept Check)
- Why do
pd.read_csv(..., comment="#")andpd.to_numeric(..., errors="coerce")eliminate 90% of manual text-cleaning headaches? - What does
center=Truedo inside.rolling(window=5, center=True).mean()(and why would omitting it cause a phase lag in time-series vibration plots)? - When should you drop a corrupted row
(
df.dropna()) vs. interpolate (df.interpolate())? - Why does noisy displacement ruin finite-difference acceleration more severely than velocity?
Guided
Practice Problem 1 (Worked Self-Check): Plant Anomaly Detector
(ME 300 Telemetry)
Load datasets/ME300_Combined_Cycle_Plant_Telemetry.csv,
compute Z-score \(z = (x -
\mu)/\sigma\) on Net_Power_MW, identify extreme
high/low operating outliers where \(|z| >
2.0\), and compute the correlation matrix
(df.corr(numeric_only=True)) showing which variable
(T_amb_C or Pressure_Ratio_rp) drives
Net_Power_MW most strongly!
Hint: df[[“T_amb_C”, “Pressure_Ratio_rp”, “Turbine_Inlet_T3_K”, “Condenser_Vac_kPa”, “Net_Power_MW”]].corr()
Higher ambient temperature \(T_{\text{amb}}\) strongly correlates
negatively with Net_Power_MW!
# Worked Practice Problem 1 Solution: Statistical Correlation & Outlier Audit (ME 300)
cc_p = next(p for p in [Path("datasets/ME300_Combined_Cycle_Plant_Telemetry.csv"), Path("../datasets/ME300_Combined_Cycle_Plant_Telemetry.csv")] if p.exists())
cc = pd.read_csv(cc_p)
mu_mw, sd_mw = cc["Net_Power_MW"].mean(), cc["Net_Power_MW"].std()
cc["z_score"] = (cc["Net_Power_MW"] - mu_mw) / sd_mw
outliers = cc[cc["z_score"].abs() > 2.0]
print(f"Power Mean = {mu_mw:.2f} MW (std = {sd_mw:.2f} MW) | |z| > 2.0 Extremes: {len(outliers)}")
print("\nCorrelations with Net_Power_MW:")
corr = cc[["T_amb_C", "P_atm_kPa", "Pressure_Ratio_rp", "Turbine_Inlet_T3_K", "Condenser_Vac_kPa", "Net_Power_MW"]].corr()["Net_Power_MW"]
print(corr.round(3))Power Mean = 573.43 MW (std = 17.48 MW) | |z| > 2.0 Extremes: 5
Correlations with Net_Power_MW:
T_amb_C -0.766
P_atm_kPa 0.282
Pressure_Ratio_rp 0.429
Turbine_Inlet_T3_K 0.239
Condenser_Vac_kPa -0.038
Net_Power_MW 1.000
Name: Net_Power_MW, dtype: float64
End-of-Chapter Practice Problems (Try Yourself!)
- Duplicate Timestamp Deduplicator: Create a small
8-row DataFrame with duplicate timestamp
t=10.0readings, average duplicates using.groupby("time_s").mean(), and confirm row uniqueness. - Hampel / IQR Sensor Spike Filter: Replace spikes
exceeding
Q3 + 1.5 * IQRor falling belowQ1 - 1.5 * IQRin a synthetic cooling-water flow log with linear interpolation. - Batch Multi-Dataset Statistical Audit: Loop over
HMT_Pin_Fin_Heat_Sink_Data.csv,Fluids_Pump_and_Pipe_Network_Data.csv, andSolar_Collector_FlatPlate_Hourly_Data.csv, checkingdf.isna().sum().sum() == 0automatically!