# 9.3 数据分析助手

对于非技术人员（运营、销售、CEO）来说，此时此刻想知道“上周北京地区的复购率是多少”，通常需要给数据分析师提需求，然后等三天。 Claude 赋予了每个人通过自然语言与数据对话的能力。

## 9.3.1 核心模式：Code Interpreter

Claude 并不直接在大脑里做数学题（容易算错），而是通过 **编写并执行代码** 来分析数据。

### 实战：CSV 深度分析

**User**: 上传文件 `user_behavior_2025.csv`。 **Questions**: “分析一下用户的留存情况，并画一个同期群分析 (Cohort Analysis) 热力图。”

**Claude Action (Step-by-Step)**:

1. **Exploration**: 先写代码看前 5 行。

   ```python
   import pandas as pd
   df = pd.read_csv('user_behavior_2025.csv')
   print(df.head())
   print(df.info())
   ```

   *Observation*: 发现 `signup_date` 是字符串，需要转换。
2. **Analysis**: 编写复杂的 Pandas 逻辑。

   ```python
   # 转换日期格式
   df['signup_date'] = pd.to_datetime(df['signup_date'])
   df['last_active'] = pd.to_datetime(df['last_active'])

   # 计算用户所属的 cohort month
   df['cohort_month'] = df['signup_date'].dt.to_period('M')

   # ... 省略中间的 pivot table 计算逻辑 ...

   # 得到 retention_matrix
   print(retention_matrix)
   ```
3. **Visualization**: 调用 Plotly 画图。

   ```python
   import plotly.express as px
   fig = px.imshow(retention_matrix,
                   text_auto='.1%',
                   title="User Retention Cohort Analysis")
   fig.write_html("cohort_heatmap.html")
   ```

**Result**: 最终直接返回一个可交互的 HTML 文件给用户。

## 9.3.2 Text-to-SQL：让非技术人员查库

对于存储在数据库（MySQL, PostgreSQL, Snowflake）中的海量数据，不能把它们都 dump 成 CSV。 这时需要 **Text-to-SQL**。

### 架构设计与 Self-Correction

一个健壮的 Text-to-SQL 系统必须包含 **错误自愈** 机制。

**Scenario**: 用户查询 “上个月销售额最高的 3 个品类”。

**Round 1 (Fail)**:

* Claude 生成: `SELECT category, sum(sales) FROM transactions WHERE month(date) = ...`
* Execution Error: `Function month() does not exist. Did you mean extract(month from date)?`
* **Claude Thinking**: “啊，这是 Postgres 数据库，不支持 `month()` 函数，我应该用 `EXTRACT` 或者 `DATE_TRUNC`。”

**Round 2 (Success)**:

* Claude 修正:

  ```sql
  SELECT
      p.category_name,
      SUM(t.amount) as total_sales
  FROM transactions t
  JOIN products p ON t.product_id = p.id
  WHERE t.created_at >= DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
    AND t.created_at < DATE_TRUNC('month', CURRENT_DATE)
  GROUP BY 1
  ORDER BY 2 DESC
  LIMIT 3;
  ```
* Result: `["Electronics", 500k], ["Home", 300k], ...`

**Explanation**: Claude 最后会把结果翻译成人话：“上个月销售额前三的品类是电子产品（50万）、家居（30万）...”。

## 9.3.3 自动可视化

数据分析的尽头是图表。不必手动去 Excel 做图。

**Prompt**:

> “请用一个交互式的 Plotly 散点图展示广告投入(x)与转化率(y)的关系，点的颜色代表地区，点的大小代表销售额。”

Claude 生成的 JSON 配置可以直接注入到前端的 ECharts 或 Plotly.js 中渲染。

## 9.3.4 真实案例：某电商运营助手

**背景**: 运营每天需要盯盘，发现流量异常。

**Agent 执行逻辑**:

1. **Schedule**: 每天早 9 点被 Cron Job 唤醒。
2. **Detection**: 运行 Python 脚本 (`scipy.stats`) 检测昨日流量是否有 > 3 sigma 的波动。
3. **Drill Down**: 如果发现异常（如 “流量暴跌 40%”），Agent 自动生成 SQL 查询：
   * “是不是某个渠道挂了？” (Group by Channel)
   * “是不是安卓端挂了？” (Group by OS)
4. **Reporting**: 最终生成一份 PDF 简报，通过 Slack 发送给运营总监，并附带一句：“初步排查是 iOS 18.2 版本的转化率异常，建议技术团队跟进。”

***

数据分析需要严谨，软件开发更需要严谨。 AI 写代码很快，但谁来保证它写得对？ 这就需要 **AI Testing & QA**。

➡️ [自动化测试与 QA](/claude_guide/di-si-bu-fen-shi-zhan-pian/09_practical/9.4_qa_test.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yeasy.gitbook.io/claude_guide/di-si-bu-fen-shi-zhan-pian/09_practical/9.3_data_analysis.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
