medium💻 Coding
Given a CSV of IoT sensor readings, detect anomalies in Python.
You have a CSV with columns: `timestamp`, `sensor_id`, `value`.
Write a Python function that:
1. Loads the CSV
2. For each sensor, flags readings that are more than **3 standard deviations** from that sensor's mean
3. Returns a DataFrame of anomalous readings with an added `z_score` column
💡 Hints (2)
- 1.Group by sensor_id, then compute mean and std per group.
- 2.pandas transform() lets you compute group stats while preserving the original index.
✅ View Solution
```python
import pandas as pd
def detect_anomalies(csv_path: str) -> pd.DataFrame:
df = pd.read_csv(csv_path, parse_dates=["timestamp"])
df["mean"] = df.groupby("sensor_id")["value"].transform("mean")
df["std"] = df.groupby("sensor_id")["value"].transform("std")
df["z_score"] = (df["value"] - df["mean"]) / df["std"]
anomalies = df[df["z_score"].abs() > 3].copy()
return anomalies[["timestamp", "sensor_id", "value", "z_score"]]
```