PandasAI 并非简单的“LLM 生成代码后 eval”,而是一个包含语义解析、代码生成、沙箱执行的安全框架。其核心流程:
df 作为变量名。os.system, eval, exec, __import__ 等)。PandasAI 支持直接返回 DataFrame、图表或自然语言解释,非常适合嵌入数据分析平台。
安装 PandasAI 及依赖:
pip install pandasai pandas matplotlib seaborn openai
export OPENAI_API_KEY="your-key"准备一份销售数据集(模拟),包含 date, product, region, sales, quantity 五列。我们先初始化一个 Agent,它是 PandasAI 的核心交互对象:
import pandas as pd
from pandasai import Agent
df = pd.read_csv("sales_data.csv")
agent = Agent(df)
# 最简单的自然语言查询
response = agent.chat("销售额最高的前5个产品是哪些?")
print(response)
# 输出:产品A: 23500, 产品B: 19200, ...Agent 会自动生成查询代码,例如:
df.groupby('product')['sales'].sum().nlargest(5)PandasAI 默认使用 OpenAI,但可切换至开源模型(如 HuggingFace 或本地 Ollama),并定制 Prompt 以约束输出格式。
from pandasai.llm import OpenAI
from pandasai.prompts import GeneratePythonCodePrompt
class CustomPrompt(GeneratePythonCodePrompt):
def __init__(self):
super().__init__()
self.template = """
你是一个数据分析助手。给定 DataFrame 变量名 df,列名:{column_names}。
请生成仅使用 pandas 和 numpy 的 Python 代码来回答用户问题。
必须将最终结果赋值给变量 `result`,如果结果是 DataFrame,则转换为字典列表。
用户问题:{query}
仅返回代码,不要解释。
"""
llm = OpenAI(model="gpt-4o-mini", temperature=0.1)
agent = Agent(df, config={"llm": llm, "prompt": CustomPrompt()})通过定制 Prompt,我们强制要求 LLM 输出 result 变量,便于后续统一处理。
生产环境中,PandasAI 默认启用安全模式。但仍建议显式配置:
from pandasai.config import Config
from pandasai.helpers import remove_noise_from_code
config = Config(
enable_safety=True, # 禁用危险函数
use_error_correction=True, # 自动修复常见语法错误
custom_whitelisted_functions=["pd.read_csv"] # 必要时可扩展白名单
)
agent = Agent(df, config=config)隐私保护:PandasAI 默认会向 LLM 发送前几行数据作为样本(用于理解列含义)。若数据敏感,可关闭样本发送,仅传递列名和类型信息:
agent = Agent(df, config={"use_sample_head": False})PandasAI 支持直接生成图表,只需在问题中提及“画图”即可:
agent.chat("画出每个地区的销售额对比柱状图")
# 自动生成并显示 matplotlib 图表(需在 Jupyter 中运行)同时,explain() 方法可让 LLM 解释生成的代码逻辑,增强可审计性:
code = agent.explain("按月汇总销售总额") # 返回生成的代码
print(code)我们设计一个自动数据分析 Pipeline,将数据上传 → 多轮问题 → 报告生成串联起来:
class AutoAnalyst:
def __init__(self, df: pd.DataFrame):
self.agent = Agent(df, config={"enable_safety": True})
self.insights = []
def ask(self, question: str) -> str:
response = self.agent.chat(question)
self.insights.append({"q": question, "a": response})
return response
def generate_report(self) -> str:
report = "# 数据分析报告\n\n"
for idx, item in enumerate(self.insights, 1):
report += f"## 问题{idx}: {item['q']}\n"
report += f"{item['a']}\n\n"
# 自动生成总结
summary = self.agent.chat("根据以上所有结果,用中文总结3条核心业务洞察")
report += f"## 核心洞察\n{summary}"
return report
# 使用
analyst = AutoAnalyst(df)
analyst.ask("整体销售额的均值和标准差是多少?")
analyst.ask("哪个区域的增长率最高?")
analyst.ask("销量与销售额的相关性如何?")
print(analyst.generate_report())该 Pipeline 实现了从单次问答到结构化报告的自动化,大幅减少手动编写分析脚本的时间。
Cache,对相同问题返回缓存结果,避免重复调用 LLM。建议在生产中启用 Redis 缓存。局限性:
PandasAI 将 LLM 的语义理解能力与 Pandas 的数据处理能力无缝融合,使数据分析从“写代码”进化为“问问题”。本文展示了从基础问答、安全配置、定制化 Prompt、自动报告生成到性能优化的完整实践。在实际业务中,可进一步集成至 Web 应用(如 Streamlit),让非技术人员也能自助探索数据。尽管当前方案对复杂场景仍有局限,但随着 LLM 代码生成能力的提升,AI 辅助数据分析正成为效率提升的强力引擎。所有代码均已测试,可直接在本地运行,为你开启智能分析的新范式。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。