乐于分享
好东西不私藏

做一个 AI 数据分析助手:从自然语言到 Pandas 报告

做一个 AI 数据分析助手:从自然语言到 Pandas 报告

现在 AI Agent 很火,但很多文章讲得太玄:规划、工具调用、多智能体……听完还是不知道怎么落地。

今天我们做一个具体项目:AI 数据分析助手。用户输入一句问题,比如“哪个城市销售额最高”,系统自动选择分析函数,输出表格结果和文字结论。

这就是 Agent 的最小形态:理解任务、调用工具、返回结果。

一、项目目标

给一份销售数据,支持 4 类自然语言问题:

  1. 1. 总销售额是多少?
  2. 2. 哪个城市销售额最高?
  3. 3. 每个月销售趋势如何?
  4. 4. 哪个品类利润率最高?

二、可视化总览:一个最小 Agent 怎么工作

AI 数据分析助手运行逻辑

这张图可以放在开头解释 Agent 的本质:不是“神秘地自动分析”,而是先判断用户意图,再调用受控工具,最后输出表格、图表和结论。

城市销售额分析示例

这张图适合放在城市销售额案例后面。公众号读者对图的感知比表格更快,一眼就能看出哪个城市贡献最大。

三、准备数据

import pandas as pd

df = pd.DataFrame({
    "date"
: pd.to_datetime([
        "2025-01-01"
, "2025-01-03", "2025-02-01",
        "2025-02-08"
, "2025-03-01", "2025-03-12"
    ]),
    "city"
: ["广州", "深圳", "广州", "上海", "深圳", "广州"],
    "category"
: ["食品", "数码", "服饰", "食品", "数码", "服饰"],
    "sales"
: [1200, 5200, 2600, 1800, 6100, 3300],
    "profit"
: [300, 1300, 600, 420, 1500, 780]
})

四、第一步:把分析能力封装成工具

def total_sales(df):
    value = df["sales"].sum()
    return
 {
        "table"
: pd.DataFrame({"指标": ["总销售额"], "数值": [value]}),
        "summary"
: f"当前数据总销售额为 {value:.0f} 元。"
    }

def
 top_city(df):
    result = (
        df.groupby("city")["sales"]
        .sum()
        .sort_values(ascending=False)
        .reset_index()
    )
    city = result.iloc[0]["city"]
    sales = result.iloc[0]["sales"]
    return
 {
        "table"
: result,
        "summary"
: f"销售额最高的城市是 {city},销售额为 {sales:.0f} 元。"
    }

def
 monthly_trend(df):
    temp = df.copy()
    temp["month"] = temp["date"].dt.to_period("M").astype(str)
    result = temp.groupby("month")["sales"].sum().reset_index()
    return
 {
        "table"
: result,
        "summary"
: "已生成按月销售趋势表,可继续绘制折线图。"
    }

def
 top_profit_category(df):
    result = df.groupby("category").agg(
        sales=("sales", "sum"),
        profit=("profit", "sum")
    ).reset_index()
    result["profit_rate"] = result["profit"] / result["sales"]
    result = result.sort_values("profit_rate", ascending=False)
    best = result.iloc[0]["category"]
    return
 {
        "table"
: result,
        "summary"
: f"利润率最高的品类是 {best}。"
    }

五、第二步:做一个简单意图识别器

正式项目可以接大模型,这里先用关键词规则跑通。

def route_question(question):
    q = question.lower()

    if
 "总销售" in q or "销售额是多少" in q:
        return
 "total_sales"
    if
 "城市" in q and ("最高" in q or "最多" in q):
        return
 "top_city"
    if
 "每月" in q or "月份" in q or "趋势" in q:
        return
 "monthly_trend"
    if
 "利润率" in q or "品类" in q:
        return
 "top_profit_category"

    return
 "unknown"

六、第三步:工具注册和调用

tools = {
    "total_sales"
: total_sales,
    "top_city"
: top_city,
    "monthly_trend"
: monthly_trend,
    "top_profit_category"
: top_profit_category
}

def
 ask_agent(question, df):
    tool_name = route_question(question)

    if
 tool_name == "unknown":
        return
 {
            "table"
: pd.DataFrame(),
            "summary"
: "暂时不支持这个问题,可以尝试问销售额、城市、趋势或利润率。"
        }

    result = tools[tool_name](df)
    result["tool"] = tool_name
    return
 result

answer = ask_agent("哪个城市销售额最高?", df)
print
("调用工具:", answer["tool"])
print
(answer["summary"])
print
(answer["table"])

这就是一个非常小的 Agent:它会根据问题选择工具。

七、第四步:自动生成图表

import matplotlib.pyplot as plt

answer = ask_agent("每个月销售趋势如何?", df)
trend = answer["table"]

plt.figure(figsize=(8, 4))
plt.plot(trend["month"], trend["sales"], marker="o")
plt.title("月度销售趋势")
plt.xlabel("月份")
plt.ylabel("销售额")
plt.tight_layout()
plt.show()

八、项目升级路线

版本
技术逻辑
规则版
关键词识别 + 固定工具
LLM版
大模型识别意图和参数
SQL版
自然语言转 SQL
Agent版
多步分析 + 自动画图 + 自动写结论
产品版
权限控制 + 日志记录 + 错误恢复

九、避坑指南

解决方案
让模型直接生成任意代码
限制可调用工具
不记录调用过程
保存 question、tool、result
结果没有表格
业务难以复核
只有文字结论
容易出现幻觉
工具太多太乱
先覆盖高频问题

总结

AI 数据分析助手的技术逻辑是:

  1. 1. 把分析能力封装成工具;
  2. 2. 识别用户问题意图;
  3. 3. 调用对应工具;
  4. 4. 返回表格、图表和文字结论;
  5. 5. 记录过程,方便排查。

别一上来就追求复杂 Agent。先把一个小助手跑通,你就真正理解了 Agent 的落地逻辑。