github star gitee star atomgit star PyPI Downloads AI编程 AI交流群

大家好,这里是程序员晚枫,正在all in AI编程实战

第20讲:AI数据分析——让AI帮你做数据洞察

AI做数据分析的优势

  • 不用写复杂SQL,用自然语言就能查数据
  • AI自动发现数据规律
  • 自动生成分析报告
  • 大幅降低数据分析门槛

1、准备工作

1
pip install openai pandas python-office

2、读取数据

1
2
3
4
5
6
7
8
9
import pandas as pd
import office

# 方法1:用pandas读取CSV
df = pd.read_csv("销售数据.csv")
print(df.head())

# 方法2:用python-office读取Excel
data = office.excel.read_excel("销售数据.xlsx")

3、让AI分析数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from openai import OpenAI

client = OpenAI(api_key="你的Key", base_url="https://api.deepseek.com")

# 把数据摘要发给AI
data_summary = f"""
数据列名:{list(df.columns)}
数据行数:{len(df)}
前5行数据:
{df.head().to_string()}
数据类型:
{df.dtypes.to_string()}
"""

response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "你是数据分析专家"},
{"role": "user", "content": f"分析以下数据,给出关键洞察和建议:\n{data_summary}"}
]
)

print(response.choices[0].message.content)

4、自然语言查询数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def text2query(question, df):
"""用自然语言查询数据"""
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{
"role": "user",
"content": f"""数据列名:{list(df.columns)}
数据示例:{df.head(3).to_string()}

请根据用户问题,生成pandas代码来查询数据。
只返回代码,不要解释。

用户问题:{question}"""
}],
temperature=0
)
code = response.choices[0].message.content
# 执行代码
result = eval(code, {"df": df, "pd": pd})
return result

# 示例
print(text2query("销售额最高的前5个产品", df))
print(text2query("每月销售趋势", df))

5、自动生成分析报告

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def generate_report(df):
"""一键生成数据分析报告"""
stats = df.describe().to_string()

response = client.chat.completions.create(
model="deepseek-chat",
messages=[{
"role": "user",
"content": f"""基于以下数据统计信息,生成一份完整的分析报告:

{stats}

报告要求:
1. 数据概览
2. 关键发现(3-5条)
3. 异常值分析
4. 趋势判断
5. 建议措施"""
}]
)
return response.choices[0].message.content

report = generate_report(df)
print(report)

# 保存为Word
office.word.create_word(report, "数据分析报告.docx")

6、实战:销售数据仪表板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import streamlit as st
import pandas as pd
from openai import OpenAI

st.title("📊 AI数据分析助手")

uploaded = st.file_uploader("上传CSV文件", type="csv")
if uploaded:
df = pd.read_csv(uploaded)
st.dataframe(df.head())

question = st.text_input("你想了解什么?")
if question and st.button("分析"):
with st.spinner("AI分析中..."):
result = text2query(question, df)
st.write(result)

下讲预告

学会了AI数据分析,下一讲我们学 AI Agent开发——让AI自主完成任务。

敬请期待!


程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。

前3讲可以试听,试听链接:https://www.bilibili.com/cheese/play/ss982042944