Skip to main content

Command Palette

Search for a command to run...

10 ways How LLMs Help With Datadrift

Published
6 min readView as Markdown
A
AI data engineer wiring agents, infra, and unapologetic build logs

🔍 Data Quality Basics

ConceptWhat It Means (Real Words)Example
AnomalyWeird data that doesn’t fit the usual patternRevenue is suddenly -$999
Schema DriftWhen the shape/columns of your data change without warningA column changes name or type
Data LineageWhere the data came from + what changed itLike a recipe history for your data

🤖 LLM + AI Help

Fancy TermWhat It Actually DoesWhy It's Cool
Isolation ForestFinds rows that look "weird" based on mathFlags unusual values, even across many columns
LOF (Local Outlier Factor)Compares how dense a row is to its neighborsCatches anomalies that are subtly off
One-Class SVMLearns what “normal” looks like, then catches weird stuffYou don’t need labeled examples
Drift DetectionNotices when your data slowly changes over timeWarns you when your model is becoming dumb

📊 Checking the Data

Check TypeWhat It MeansExample
CompletenessAre any values missing?100 rows, but age column has 30 blanks
ConsistencyDo the formats or values match what we expect?Someone typed "Ten" instead of 10
AccuracyIs it correct?Customer age says 212 😬
TimelinessIs it fresh and updated?Data from 3 weeks ago... not helpful

🛠️ Tools in the Detective Kit

ToolWhat It Does
PandasLoad and explore the data in Python
Great ExpectationsWrite rules like “this column should never be null”
dbtTransforms SQL data + tests it before it breaks stuff
OpenAI/ClaudeReads your data, explains changes, helps write fix code
Kafka(Advanced) Streams new data in real-time for validation
StreamlitMakes a pretty interface for humans to see alerts 📊

Absolutely! Here’s a side-by-side “Before → After” for each sample. I’ll show what you see when you run the code — so you get the full picture, not just the script. 🧪🐼


🧪 1. Great Expectations — Check for Nulls

✅ Code:

import great_expectations as ge
import pandas as pd

df = pd.DataFrame({
    "user_id": [101, 102, 103],
    "revenue": [99.9, None, 150.0]
})

ge_df = ge.from_pandas(df)
result = ge_df.expect_column_values_to_not_be_null("revenue")
print(result)

🟥 Output:

{
  "success": false,
  "unexpected_index_list": [1],
  "unexpected_count": 1,
  "unexpected_percent": 33.3,
  "result": {
    "element_count": 3,
    "missing_count": 1
  }
}

❌ One row has None — GE flagged it!


🛠 2. dbt — SQL Clean + Test

📥 Before: Raw SQL (bad data)

idrevenuestatus
1$120complete
2nullpending

➕ dbt SQL transforms it:

SELECT
  id,
  CAST(REPLACE(revenue, '$', '') AS FLOAT) AS revenue_cleaned
FROM raw.orders
WHERE status = 'complete'

📤 Output Table:

idrevenue_cleaned
1120.0

✅ dbt cleaned and filtered data — and tested revenue_cleaned is not null!


📡 3. Kafka Stream (Faust-style)

⚠️ Input Streaming Message:

{"user_id": 201, "revenue": -500}

⛔ Output in console:

🚨 Bad row detected: {'user_id': 201, 'revenue': -500}

You caught the issue while streaming, not after!


🧠 4. Isolation Forest

Input:

"revenue": [100, 120, 115, 99, 5000]

Output:

   revenue  anomaly
0      100        1
1      120        1
2      115        1
3       99        1
4     5000       -1

🚨 Row 4 (value = 5000) is flagged as anomaly (-1)


🧠 5. Local Outlier Factor (LOF)

Input:

"age": [22, 24, 23, 25, 99],
"score": [88, 89, 87, 90, 20]

Output:

   age  score  anomaly
0   22     88        1
1   24     89        1
2   23     87        1
3   25     90        1
4   99     20       -1

🚨 Last row is too far off — LOF says “not like the others.”


🧠 6. One-Class SVM

Input:

"metric": [0.5, 0.6, 0.55, 0.52, 3.0]

Output:

   metric  anomaly
0    0.50        1
1    0.60        1
2    0.55        1
3    0.52        1
4    3.00       -1

🚨 Row 4 is way off — flagged as novelty/outlier


🧠 7. Drift Detection (JS Divergence)

Input Histograms:

yesterday = [100, 120, 110, 115]
today = [300, 400, 500, 600]

Output:

JS Divergence: 0.6931

🧠 High number (closer to 1) = serious distribution drift


🤖 How LLMs Help with Detective Pandas (Schema + Quality)

🧪 Use Case💡 LLM Role (What It Does)🛠️ Real Example
1. Schema Drift💬 Detect changes between old and new schema, explain what changedrevenue column changed from float → string; suggest converting it back”
2. Fix Code for Drift🛠️ Suggest Python code to clean or cast columnsdf['revenue'] = df['revenue'].str.replace('$', '').astype(float)
3. Explain Quality Errors📖 Translate Great Expectations output into human-readable alerts“1 row failed — revenue column has a null at index 3”
4. Auto-generate GE rules🛠️ Given a sample dataset, LLM writes a quality spec (e.g., non-null, value range)"expect revenue to be between 0 and 10000"
5. Detect anomalies🧠 Suggest and implement Isolation Forest or LOF automatically“Try IsolationForest with contamination=0.1”
6. Create dashboards or reports🧾 Write markdown or Streamlit summaries of what’s wrong“Data drift detected in signup_date, suggest histogram comparison”
7. Explain statistical tests🧠 Makes advanced stuff (like JS divergence) sound human“Your data distribution changed — see JS score = 0.68 → consider retraining”
8. Suggest dbt tests✍️ Writes schema.yml entries and SQL model testsAdds: tests: [not_null, accepted_range] to YAML
9. Stream Monitoring🧪 Writes logic to plug anomaly detection into a Kafka stream or Faust appCreates Python code for “alert if revenue < 0 in real-time stream”
10. Root Cause Analysis🔍 Scans logs, schemas, recent changes to guess what broke what“Nulls started after March 20 deploy. Check new upstream API version.”

🧠 Prompt Example

"Hey Claude, here's the schema yesterday and today. What's changed and how can I fix it in pandas?"

📥 Input:

Schema Day 1: {"revenue": "float", "email": "string"}
Schema Day 2: {"revenue": "string", "email": "string"}

📤 Output:

"Column revenue changed from float to string. Try:
df['revenue'] = df['revenue'].str.replace('$', '').astype(float)"


✅ What LLMs Can Do

  • Understand what’s wrong

  • Suggest or write the fix

  • Automate report generation

  • Explain scary math

  • Help non-engineers understand issues

❌ What LLMs Can’t Do

  • Access your database (you must provide input)

  • Guarantee fixes are perfect (always review!)

  • Run the code — you still execute it

More from this blog

Anix Lynch – Technical Notes & Engineering Playbooks

176 posts

Deploying mode 🚀 one csv at a time.