Lesson
17: Tabular Engineering Telemetry with pandas (CSVs, Tables
& Filtering)
The βBoring Stuffβ Problem: Excel Breaks When Columns Need Cleaning & Formulas Across 120 Rows
Suppose you open a CSV file like
ME200_Saturated_Water_Temp_Table.csv (76 rows, 10 columns,
erratic spacing in column headers) or
ME300_Combined_Cycle_Plant_Telemetry.csv (120 hourly
gas-steam power plant records). Doing VLOOKUPs, filtering
peak-efficiency rows, or computing new thermodynamic ratios by dragging
Excel formulas across hundreds of cells gets messy fast.
pandas gives Python a high-speed
programmable spreadsheet called a
DataFrame:
pd.read_csv(path)reads entire CSVs into named columns in 1 line,df.columns = [" ".join(c.split()) for c in df.columns]fixes messy headers instantaneously,df["new_col"] = ...adds physics columns across all rows in microseconds,df[df["col"] > thresh]filters test points without mouse clicks!
Core pandas
Operations Cheat Sheet
| Operation | Code Example | Engineering Result |
|---|---|---|
| Load CSV | df = pd.read_csv(path) |
Reads header + typed columns |
| Inspect top/stats | df.head(),
df.describe() |
First 5 rows; count/mean/min/max/std |
| Select column(s) | df["Net_Power_MW"],
df[["T_amb_C", "Net_Power_MW"]] |
1D Series or
sub-DataFrame |
| Filter rows | df[(df["T_amb_C"] > 30) & (df["Pressure_Ratio_rp"] > 18)] |
Parentheses & and
| required! |
| Group summary | df.groupby("Suction_Status")["Pump_Efficiency_eta"].mean() |
Instant summary by regime/category |
| Export CSV | df.to_csv("clean.csv", index=False) |
Always pass index=False so
row numbers donβt clutter! |
Watch Out! Two Classic
pandas Bugs
- Use
&and|, NOTand/or, Inside Row Filters: Pythonβsandcrashes on pandas boolean columns (ValueError: The truth value of a Series is ambiguous). Wrap each test in parentheses:(df["A"] > 1) & (df["B"] < 5). - Always Pass
index=Falseondf.to_csv(..., index=False): Otherwise pandas writes an uglyUnnamed: 0index column on every re-save!
import pandas as pd
from pathlib import Path
# Example 1 (ME 300 Combined-Cycle Plant Telemetry): Loading, Vector Physics Columns & Group Summary
cc_path = next(
p for p in [
Path("datasets/ME300_Combined_Cycle_Plant_Telemetry.csv"),
Path("../datasets/ME300_Combined_Cycle_Plant_Telemetry.csv"),
] if p.exists()
)
df = pd.read_csv(cc_path)
# Add theoretical Combined-Cycle Efficiency check right across all 120 rows!
eta_b = df["Brayton_Eff_pct"] / 100.0
eta_r = df["Rankine_Eff_pct"] / 100.0
df["Calc_CC_Eff_pct"] = (eta_b + eta_r - eta_b * eta_r) * 100.0
df["Ambient_Bin"] = pd.cut(df["T_amb_C"], bins=[0, 15, 25, 45], labels=["Cool (<15C)", "Mild (15-25C)", "Hot (>25C)"])
print("=== Combined-Cycle Plant Summary (120 Operating Points) ===")
print(df[["T_amb_C", "Pressure_Ratio_rp", "Calc_CC_Eff_pct", "Net_Power_MW"]].describe().round(2))
print("\n=== Mean Power & Efficiency by Ambient Temperature Bin ===")
summary = df.groupby("Ambient_Bin", observed=False)[["Calc_CC_Eff_pct", "Net_Power_MW"]].agg(["mean", "max"]).round(2)
print(summary)=== Combined-Cycle Plant Summary (120 Operating Points) ===
T_amb_C Pressure_Ratio_rp Calc_CC_Eff_pct Net_Power_MW
count 120.00 120.00 120.00 120.00
mean 20.65 17.73 70.68 573.43
std 8.14 2.33 1.45 17.48
min 5.06 14.03 67.29 530.59
25% 14.62 15.76 69.90 561.78
50% 20.98 17.40 70.71 574.73
75% 25.86 19.64 71.60 587.72
max 35.68 21.95 73.67 606.18
=== Mean Power & Efficiency by Ambient Temperature Bin ===
Calc_CC_Eff_pct Net_Power_MW
mean max mean max
Ambient_Bin
Cool (<15C) 71.48 73.67 588.18 606.18
Mild (15-25C) 70.97 73.65 575.82 599.43
Hot (>25C) 69.53 71.84 556.17 586.31
# Example 2 (Fluid Mechanics + ME 200 Messy Header Normalization): Clean Lookup & Conditioned Filtering
sat_path = next(p for p in [Path("datasets/ME200_Saturated_Water_Temp_Table.csv"), Path("../datasets/ME200_Saturated_Water_Temp_Table.csv")] if p.exists())
sat_df = pd.read_csv(sat_path)
print("Before cleaning headers:", list(sat_df.columns[:4]))
sat_df.columns = [" ".join(c.strip().split()) for c in sat_df.columns]
sat_df["h_fg (kJ/kg)"] = sat_df["Enthalpy (hg, kJ/kg)"] - sat_df["Enthalpy (hf, kJ/kg)"]
print("Cleaned headers :", list(sat_df.columns[:4]))
# Find operating rows between 100 C and 200 C for industrial process steam
proc = sat_df[(sat_df["Temp. (C)"] >= 100.0) & (sat_df["Temp. (C)"] <= 200.0)]
print(f"\nProcess Steam Band (100-200 C): {len(proc)} table rows")
print(proc[["Temp. (C)", "Press. (bar)", "Enthalpy (hf, kJ/kg)", "Enthalpy (hg, kJ/kg)", "h_fg (kJ/kg)"]].iloc[::4].to_string(index=False))Before cleaning headers: ['Temp. (C)', 'Press. (bar)', 'Volume (vf, m3/kg)', 'Internal Energy (uf, kJ/kg)']
Cleaned headers : ['Temp. (C)', 'Press. (bar)', 'Volume (vf, m3/kg)', 'Internal Energy (uf, kJ/kg)']
Process Steam Band (100-200 C): 11 table rows
Temp. (C) Press. (bar) Enthalpy (hf, kJ/kg) Enthalpy (hg, kJ/kg) h_fg (kJ/kg)
100.0 1.0142 419.17 2675.6 2256.43
140.0 3.6154 589.16 2733.4 2144.24
180.0 10.0280 763.05 2777.2 2014.15
Practice Questions (Concept Check)
- Why does
df[df["A"] > 5 and df["B"] < 10]fail inpandas, and what is the correct syntax? - What does
index=Falseprevent when callingdf.to_csv("out.csv", index=False)? - How do
df.iloc[0:3]anddf.loc[...]differ when selecting rows? - Look at Example 1: why did ambient air temperature
(
Hot >25C) reduce combined-cycle net MW output? (Physical check: compressor work increases and air density drops when air heats up!)
Guided
Practice Problem 1 (Worked Self-Check): Pump Operating Regime Groupby
Audit (Fluids)
Load datasets/Fluids_Pump_and_Pipe_Network_Data.csv into
a DataFrame pump_df, add a calculated
NPSH_Margin_m = NPSH_Available_m - NPSH_Required_m column,
group by Suction_Status to show average flow rate,
efficiency, and NPSH margin, and display the top 3 highest-efficiency
operating points!
Hint: pump_df.sort_values(βPump_Efficiency_etaβ, ascending=False).head(3)
Combining .groupby() + .sort_values()
answers fleet triage questions in 3 lines.
# Worked Practice Problem 1 Solution: Pandas Pump Network Diagnostics
pp = next(p for p in [Path("datasets/Fluids_Pump_and_Pipe_Network_Data.csv"), Path("../datasets/Fluids_Pump_and_Pipe_Network_Data.csv")] if p.exists())
pump_df = pd.read_csv(pp)
pump_df["NPSH_Margin_m"] = pump_df["NPSH_Available_m"] - pump_df["NPSH_Required_m"]
print("Mean Metrics by Suction Status:")
print(pump_df.groupby("Suction_Status")[["Flow_Rate_Q_L_s", "Pump_Efficiency_eta", "NPSH_Margin_m"]].mean().round(3))
print("\nTop 3 Highest-Efficiency Flow Points:")
print(pump_df.sort_values("Pump_Efficiency_eta", ascending=False).head(3)[["Flow_Rate_Q_L_s", "Pump_Head_Hpump_m", "Pump_Efficiency_eta", "Suction_Status"]].to_string(index=False))Mean Metrics by Suction Status:
Flow_Rate_Q_L_s Pump_Efficiency_eta NPSH_Margin_m
Suction_Status
CAVITATION! 125.0 0.804 -6.555
Safe 50.0 0.564 2.562
Top 3 Highest-Efficiency Flow Points:
Flow_Rate_Q_L_s Pump_Head_Hpump_m Pump_Efficiency_eta Suction_Status
110.0 29.62 0.8448 CAVITATION!
100.0 33.50 0.8400 CAVITATION!
120.0 25.36 0.8352 CAVITATION!
End-of-Chapter Practice Problems (Try Yourself!)
- Fluids Viscosity Temperature Sensitivity
(
Fluids): LoadFluids_Property_and_Viscosity_Table.csv, compute the ratio \(\nu_{\text{water}}(0^\circ\text{C}) / \nu_{\text{water}}(100^\circ\text{C})\) and Air/Water density ratio at \(20^\circ\text{C}\). - Solar Peak Window Selector
(
Solar Thermal): LoadSolar_Collector_FlatPlate_Hourly_Data.csv, filter hours whereefficiency_percent >= 55.0, and compute mean \(G_T\) and mean \(U_L\) during peak efficiency hours. - Heat Exchanger Type Ranking (
HMT): LoadHMT_Heat_Exchanger_NTU_Data.csv, extract rowNTU == 2.0, and melt/compare effectiveness across Counterflow, Parallel-Flow, Shell-Tube, and Crossflow atCr = 1.0.