Build an Automated EDA System Using Python and LLMs

Whenever I begin a new machine learning project, the biggest challenge isn’t picking an algorithm. Instead, I spend hours writing the same Pandas scripts to figure out what’s wrong with a raw dataset. An Automated EDA System built with Python and LLMs fixes this by quickly turning any CSV or Excel file into an interactive visual report with clear, human-readable insights.

Rather than building exploratory notebooks from scratch, you can use statistical profiling along with a free Large Language Model API to automatically explain anomalies and suggest what to do next.

Why Combine Deterministic Python Stats with an LLM?

One mistake I often see beginners make is uploading a whole raw CSV file directly into an LLM prompt. This doesn’t work well in practice. Large datasets go over context limits, raw tables use up free API quotas quickly, and LLMs can miscalculate simple things like averages or quantiles when handling lots of rows.

A better engineering approach is to clearly separate each part of the process:

  1. Python, Pandas, and NumPy take care of the calculations, like missing-value percentages, outliers using the interquartile range, distribution skewness, and Pearson correlations.
  2. Plotly turns these statistics into interactive charts you can view in your browser, making it easy to spot any anomalies.
  3. The LLM API only gets a compact JSON summary of these metrics. It acts like a senior analyst by finding patterns and suggesting preprocessing steps.

Building an Automated EDA System Using Python and LLMs

Step 1: Set Up Your Free Environment

This workflow uses open-source Python libraries and the free tier of Google AI Studio, which lets you access the API without needing billing or a credit card. Start by installing these packages:

pip install pandas numpy plotly openpyxl google-genai
Book cover: Cracking your First AI/ML Interview by Aman Kharwal

Cracking your First AI/ML Interview

Everything you need to turn your AI/ML skills into real job offers.

Get it on Google Play Books By Aman Kharwal

Next, get a free API key from Google AI Studio. To keep things simple for both Jupyter notebooks and local editors, we’ll define the key as a constant in our Python script instead of using environment variables. Always make sure not to share real API keys in any public repository.

Step 2: Build the Statistical Profiling Engine

Before we create charts or use an LLM, we need a profiling engine that works with both .csv and .xlsx files. In real projects, it’s common to deal with messy spreadsheets that have mixed column types and skewed distributions.

The module below sets up our GEMINI_API_KEY constant and pulls out dataset dimensions, duplicate rows, missing value percentages, distribution skewness, and outlier counts using the Interquartile Range (IQR) rule. Each metric is cast to native Python int and float types so the dictionary can be easily turned into JSON without NumPy type errors:

import json
from pathlib import Path
import numpy as np
import pandas as pd
import plotly.express as px
from google import genai

# Paste your free Google AI Studio API key directly here
GEMINI_API_KEY = "your api key"


def load_dataset(file_path: str) -> pd.DataFrame:
    """Load a CSV or Excel dataset into a Pandas DataFrame."""
    ext = Path(file_path).suffix.lower()
    if ext == ".csv":
        return pd.read_csv(file_path)
    if ext in {".xlsx", ".xls"}:
        return pd.read_excel(file_path)
    raise ValueError(f"Unsupported file format: {ext}. Use .csv or .xlsx.")


def profile_dataset(df: pd.DataFrame) -> dict:
    """Compute missingness, IQR outliers, distributions, and correlations."""
    numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
    categorical_cols = df.select_dtypes(exclude=[np.number]).columns.tolist()

    # 1. Missing values summary
    missing_summary = {}
    for col in df.columns:
        missing_count = int(df[col].isna().sum())
        if missing_count > 0:
            missing_summary[col] = {
                "missing_count": missing_count,
                "missing_pct": round((missing_count / len(df)) * 100, 2),
            }

    # 2. Numeric distributions and IQR outlier detection
    numeric_summary = {}
    for col in numeric_cols:
        series = df[col].dropna()
        if series.empty:
            continue

        q1 = float(np.percentile(series, 25))
        q3 = float(np.percentile(series, 75))
        iqr = q3 - q1
        lower_bound = q1 - 1.5 * iqr
        upper_bound = q3 + 1.5 * iqr
        outliers = series[(series < lower_bound) | (series > upper_bound)]

        numeric_summary[col] = {
            "mean": round(float(series.mean()), 3),
            "median": round(float(series.median()), 3),
            "std": round(float(series.std()), 3),
            "min": round(float(series.min()), 3),
            "max": round(float(series.max()), 3),
            "skewness": round(float(series.skew()), 3),
            "outlier_count": int(len(outliers)),
            "outlier_pct": round((len(outliers) / len(series)) * 100, 2),
            "iqr_bounds": [round(lower_bound, 3), round(upper_bound, 3)],
        }

    # 3. Categorical patterns
    categorical_summary = {}
    for col in categorical_cols:
        series = df[col].dropna().astype(str)
        top_values = series.value_counts().head(3).to_dict()
        categorical_summary[col] = {
            "unique_values": int(series.nunique()),
            "top_frequencies": {str(k): int(v) for k, v in top_values.items()},
        }

    # 4. Strongest feature correlations
    strong_correlations = []
    if len(numeric_cols) >= 2:
        corr_matrix = df[numeric_cols].corr(method="pearson")
        for i in range(len(numeric_cols)):
            for j in range(i + 1, len(numeric_cols)):
                r_val = corr_matrix.iloc[i, j]
                if pd.notna(r_val) and abs(r_val) >= 0.4:
                    strong_correlations.append({
                        "feature_1": numeric_cols[i],
                        "feature_2": numeric_cols[j],
                        "pearson_r": round(float(r_val), 3),
                    })
        strong_correlations.sort(key=lambda x: abs(x["pearson_r"]), reverse=True)

    return {
        "shape": {"rows": int(df.shape[0]), "columns": int(df.shape[1])},
        "duplicate_rows": int(df.duplicated().sum()),
        "numeric_columns": numeric_cols,
        "categorical_columns": categorical_cols,
        "missing_values": missing_summary,
        "numeric_distributions_and_outliers": numeric_summary,
        "categorical_patterns": categorical_summary,
        "strong_correlations": strong_correlations,
    }

Step 3: Generate Interactive Plotly Visualizations

Static charts make it hard to look at individual outliers or check exact correlation values. By exporting Plotly figures to a single HTML file, anyone on your team can open the interactive report in their browser without needing to run Python.

This function creates a missing-value bar chart if there are missing entries, a Pearson correlation heatmap, and distribution histograms with box plots for your three most skewed numeric features:

def generate_visualizations(
    df: pd.DataFrame, profile: dict, output_html: str = "eda_report.html"
) -> str:
    """Create interactive Plotly charts and save them as a single HTML report."""
    figures = []

    # Chart 1: Missing Values Breakdown (rendered when missing entries exist)
    if profile["missing_values"]:
        miss_df = pd.DataFrame([
            {"Column": col, "Missing (%)": info["missing_pct"]}
            for col, info in profile["missing_values"].items()
        ]).sort_values("Missing (%)", ascending=False)

        fig_miss = px.bar(
            miss_df,
            x="Column",
            y="Missing (%)",
            title="Missing Values Percentage by Column",
            text="Missing (%)",
            color_discrete_sequence=["#5170ff"],
        )
        figures.append(fig_miss)

    # Chart 2: Correlation Heatmap
    num_cols = profile["numeric_columns"]
    if len(num_cols) >= 2:
        corr = df[num_cols].corr().round(2)
        fig_corr = px.imshow(
            corr,
            text_auto=True,
            color_continuous_scale="RdBu_r",
            zmin=-1,
            zmax=1,
            title="Feature Correlation Heatmap (Pearson)",
        )
        figures.append(fig_corr)

    # Chart 3: Top 3 Most Skewed Numeric Distributions with Box Plots
    num_stats = profile["numeric_distributions_and_outliers"]
    top_skewed = sorted(
        num_stats.keys(),
        key=lambda c: abs(num_stats[c]["skewness"]),
        reverse=True,
    )[:3]

    for col in top_skewed:
        fig_dist = px.histogram(
            df,
            x=col,
            marginal="box",
            nbins=30,
            title=f"Distribution & Outliers: {col} (Skewness: {num_stats[col]['skewness']})",
            color_discrete_sequence=["#5170ff"],
        )
        figures.append(fig_dist)

    # Assemble all Plotly figures into one standalone HTML file
    html_blocks = [
        "<html><head><title>Automated EDA Visual Report</title></head>"
        "<body style='font-family: sans-serif; max-width: 1100px; margin: auto; padding: 24px;'>"
        "<h1>Automated Exploratory Data Analysis Report</h1>"
    ]
    for fig in figures:
        html_blocks.append(fig.to_html(full_html=False, include_plotlyjs="cdn"))
    html_blocks.append("</body></html>")

    Path(output_html).write_text("\n".join(html_blocks), encoding="utf-8")
    return output_html

Step 4: Interpret Results with a Free LLM API

Now we send the statistical profile to gemini-3.5-flash-lite using the official google-genai SDK and our GEMINI_API_KEY. Since we only send a compact JSON summary instead of raw spreadsheet rows, each run uses just a few hundred tokens. This keeps us within free-tier limits and gives better analytical results.

The prompt tells the model to act like a practical data scientist. It should highlight important relationships, point out data quality risks, and suggest specific cleaning or feature engineering steps:

def interpret_with_llm(profile: dict) -> str:
    """Send the structured statistical profile to Gemini's free tier for insights."""
    if not GEMINI_API_KEY or GEMINI_API_KEY == "YOUR_FREE_GEMINI_API_KEY":
        raise ValueError("Replace YOUR_FREE_GEMINI_API_KEY with your Google AI Studio key.")

    client = genai.Client(api_key=GEMINI_API_KEY)
    prompt = f"""
You are a senior Data Scientist reviewing an automated statistical profile of a dataset.
Analyze the JSON metrics below and provide a clear, structured report covering:
1. Executive Overview & Key Patterns
2. Data Quality & Missing Value Risks
3. Anomaly & Outlier Explanations (reference exact numbers and skewness)
4. Actionable Cleaning, Feature Engineering, and Modeling Recommendations

Dataset Statistical Profile:
{json.dumps(profile, indent=2)}
"""
    response = client.models.generate_content(
        model="gemini-3.5-flash-lite",
        contents=prompt,
    )
    return response.text

Step 5: Run the Workflow on a Dataset

To test the whole pipeline without downloading extra files, we can use the classic restaurant tips dataset that comes with Plotly Express. It has numeric bills, tip amounts, party sizes, and categorical columns like day and dining time, so our profiler can find real correlations and skewed distributions.

We save this built-in dataset as a CSV file and then run the full workflow from start to finish:

def run_automated_eda(file_path: str, report_html: str = "eda_report.html") -> None:
    """Execute the full Automated EDA workflow on a CSV or Excel file."""
    print(f"Loading dataset: {file_path}")
    df = load_dataset(file_path)

    print("Running statistical profiling...")
    profile = profile_dataset(df)

    print("Generating interactive Plotly visualizations...")
    saved_html = generate_visualizations(df, profile, output_html=report_html)
    print(f"Visual report saved to: {saved_html}")

    print("Generating AI-powered analytical insights...\n")
    insights = interpret_with_llm(profile)
    print(insights)


if __name__ == "__main__":
    # Load the built-in 'tips' dataset directly from Plotly Express
    builtin_df = px.data.tips()
    sample_file = "tips_dataset.csv"
    builtin_df.to_csv(sample_file, index=False)

    run_automated_eda(sample_file)

When you run the script, it creates eda_report.html for you to explore visually and prints a structured executive summary of the dataset right in your console.

The Takeaway

An automated EDA system can speed up your initial analysis, but keep two things in mind. First, never send personal or confidential company data to external APIs. Use aggregated summaries or run a local model with Ollama if privacy is important. Second, treat LLM insights as starting points, not final answers. Domain knowledge is still needed to decide if an extreme outlier is a data error or a real high-value event.

Creating reusable tools like this is a great habit for any AI engineer. By combining accurate Python code with LLMs for interpretation, you can move beyond repetitive exploratory scripts and start building real analytical systems.

I hope you enjoyed this article about building an automated EDA system with Python and LLMs. If you want more AI and machine learning tips, you’re welcome to follow me on Instagram.

Aman Kharwal
Aman Kharwal

AI/ML Engineer | Published Author. My aim is to decode data science for the real world in the most simple words.

Articles: 2277

Leave a Reply