Python中有一个streamlit库,Streamlit 的美妙之处在于您可以直接在 Python 中创建 Web 应用程序,而无需了解 HTML、CSS 或 JavaScrip,今天我们就用streamlit来写一个把Excel表格内容转化成web可视化图表的程序。


【资料图】

准备工作:安装依赖库

pip install plotly pip install streamlit pip install pandas pip install openpyxl pip install Pillow

数据展示:

代码实现:

1.导入库

import pandas as pdimport streamlit as stimport plotly.express as pxfrom PIL import Image

2.读取数据

### --- 加载数据excel_file = "Survey_Results_2021.xlsx"#文件地址sheet_name = "DATA"#sheet名称df = pd.read_excel(excel_file,                   sheet_name=sheet_name,                   usecols="B:D",#列取值范围                   header=3)df_participants = pd.read_excel(excel_file,                                sheet_name= sheet_name,                                usecols="F:G",                                header=3)df_participants.dropna(inplace=True)

3.网页设置

st.set_page_config(page_title="调查结果")#网页标题st.title("2021员工考核结果") #标题st.subheader("筛选条件")#子标题# --- 筛选条件department = df["部门"].unique().tolist() #部门列去重后结果ages = df["年龄"].unique().tolist()age_selection = st.slider("年龄:",                        min_value= min(ages),                        max_value= max(ages),                        value=(min(ages),max(ages)))department_selection = st.multiselect("部门:",                                    department,                                    default=department)# --- 基于条件筛选的过滤mask = (df["年龄"].between(*age_selection)) & (df["部门"].isin(department_selection))number_of_result = df[mask].shape[0]st.markdown(f"*参与人数: {number_of_result}*")# --- 筛选后的数据df_grouped = df[mask].groupby(by=["评分"]).count()[["年龄"]]df_grouped = df_grouped.rename(columns={"年龄": "人数"})df_grouped = df_grouped.reset_index()# --- 柱状图bar_chart = px.bar(df_grouped,                   x="评分",                   y="人数",                   text="人数",                   color_discrete_sequence = ["#F63366"]*len(df_grouped),                   template= "plotly_white")st.plotly_chart(bar_chart)# --- 展示图片和数据col1, col2 = st.beta_columns(2)image = Image.open("images/wx.png")print(image)col1.image(image,        caption="关注公众号,更多有趣内容等你发现",        use_column_width=True)col2.dataframe(df[mask], width=480, height=400)# --- PLOT PIE CHARTpie_chart = px.pie(df_participants,                title="参与人数分布概况",                values="参与人数",                names="部门统计")st.plotly_chart(pie_chart)

4.运行(需要cmd或者终端到py文件路径下运行)

streamlit run app.py

5.展示效果(执行步骤4后会自动弹出默认浏览器窗口,也可以直接访问上图中的地址)

年龄支持滑动选择,部门支持多选,最终筛选两个条件下的数据来展示

感兴趣的小伙伴可以参考上面的代码和数据自行实践一下,对于不会编程的小伙伴,我会在明天用工具来给大家展示一下如何快速实现数据可视化

公众号「python玩转」后台回复「图表源码」可以获得源码一份

推荐内容