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 pd
import streamlit as st
import plotly.express as px
from 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 CHART
pie_chart = px.pie(df_participants,
title='参与人数分布概况',
values='参与人数',
names='部门统计')
st.plotly_chart(pie_chart)
4.运行(需要cmd或者终端到py文件路径下运行)
streamlit run app.py
5.展示效果(执行步骤4后会自动弹出默认浏览器窗口,也可以直接访问上图中的地址)
年龄支持滑动选择,部门支持多选,最终筛选两个条件下的数据来展示
感兴趣的小伙伴可以参考上面的代码和数据自行实践一下,对于不会编程的小伙伴,我会在明天用工具来给大家展示一下如何快速实现数据可视化
公众号「python玩转」后台回复「图表源码」可以获得源码一份