:开发一个 AI 数据看板——用 Streamlit 上传文件自动分析)
AI 工具开发实战7开发一个 AI 数据看板——用 Streamlit 一行代码部署数据分析应用前几篇都是 CLI 和插件工具这篇做一个带界面的——AI 数据看板。用 Streamlit Pandas LLM上传 Excel/CSVAI 自动分析数据、生成图表和洞察。工具做什么上传 Excel/CSV 文件 ↓ 1. 自动预览数据前 10 行 2. AI 分析数据特征分布、异常值、趋势 3. 生成可视化图表 4. 对话式数据问答上个月销售额最高的品类是什么项目结构aidash/ ├── app.py # Streamlit 主程序 ├── analyzer.py # AI 数据分析 ├── requirements.txt └── .env核心代码# app.pyimportstreamlitasstimportpandasaspdimportplotly.expressaspxfromanalyzerimportAIAnalyzer st.set_page_config(page_titleAI 数据看板,layoutwide)st.title( AI 数据看板)# 初始化 AI 分析器ifanalyzernotinst.session_state:st.session_state.analyzerAIAnalyzer()# 上传文件uploaded_filest.file_uploader(上传 Excel 或 CSV 文件,type[csv,xlsx])ifuploaded_file:# 读取数据ifuploaded_file.name.endswith(.csv):dfpd.read_csv(uploaded_file)else:dfpd.read_excel(uploaded_file)st.session_state.dfdf# 数据预览col1,col2,col3,col4st.columns(4)col1.metric(行数,len(df))col2.metric(列数,len(df.columns))col3.metric(缺失值,df.isna().sum().sum())col4.metric(数值列,len(df.select_dtypes(number).columns))# 数据表格withst.expander( 数据预览,expandedTrue):st.dataframe(df.head(20),use_container_widthTrue)# AI 分析ifst.button( AI 分析数据,typeprimary):withst.spinner(AI 正在分析...):analysisst.session_state.analyzer.analyze(df)# 数据洞察ifanalysis.get(insights):st.subheader( 关键洞察)forinsightinanalysis[insights]:st.info(insight)# 推荐图表ifanalysis.get(charts):st.subheader( 推荐图表)forchartinanalysis[charts]:col_namechart[column]chart_typechart[type]ifchart_typebarandcol_nameindf.columns:countsdf[col_name].value_counts().head(10)figpx.bar(xcounts.index,ycounts.values,titlef{col_name}分布)st.plotly_chart(fig,use_container_widthTrue)elifchart_typelineandcol_nameindf.columns:ifpd.api.types.is_numeric_dtype(df[col_name]):figpx.line(df[col_name].dropna().head(200),titlef{col_name}趋势)st.plotly_chart(fig,use_container_widthTrue)# 对话式问答st.subheader( 数据问答)questionst.text_input(输入你的数据问题,placeholder例如销售额最高的品类是哪个)ifquestion:withst.spinner(AI 正在回答...):answerst.session_state.analyzer.ask(df,question)st.markdown(answer)# analyzer.pyfromopenaiimportOpenAIimportosimportjsonfromdotenvimportload_dotenv load_dotenv()clientOpenAI(api_keyos.getenv(DEEPSEEK_API_KEY),base_urlhttps://api.deepseek.com/v1,)classAIAnalyzer:AI 数据分析引擎。defanalyze(self,df):分析数据并返回洞察和图表建议。# 准备数据摘要summaryself._get_data_summary(df)responseclient.chat.completions.create(modeldeepseek-chat,messages[{role:system,content:f你是一个数据分析专家。分析以下数据摘要返回 JSON 格式 {{ insights: [洞察1, 洞察2, ...], charts: [{{column: 列名, type: bar|line|pie, reason: 原因}}, ...] }} 数据摘要{summary}}],temperature0.3,)try:returnjson.loads(response.choices[0].message.content)except:return{insights:[],charts:[]}defask(self,df,question):回答数据相关问题。summaryself._get_data_summary(df)sampledf.head(5).to_string()responseclient.chat.completions.create(modeldeepseek-chat,messages[{role:system,content:f基于以下数据回答用户问题。\n\n数据概览{summary}\n\n数据样本\n{sample}},{role:user,content:question,}],temperature0.3,)returnresponse.choices[0].message.contentdef_get_data_summary(self,df):生成数据摘要。returnf 形状{df.shape[0]}行 x{df.shape[1]}列 列名{list(df.columns)}数据类型{dict(df.dtypes.astype(str))}数值列统计{df.describe().to_string()iflen(df.select_dtypes(number).columns)0else无}缺失值{dict(df.isna().sum())}使用方式pipinstallstreamlit pandas plotly openai python-dotenv streamlit run app.py浏览器打开http://localhost:8501上传文件 → AI 自动分析 → 生成图表。总结一个实用的 AI 数据看板核心三步Streamlit 做界面一行代码部署Pandas 处理数据LLM 做分析和问答比传统 BI 工具灵活比手动分析快 10 倍。本文是《AI 开发者工具链实战》系列的第 7 篇。如果觉得有用欢迎点赞 收藏 关注。