CSDN如何构建一个交互式数据分析 Web 应用?


CSDN如何构建一个交互式数据分析 Web 应用?
本文插图
作者 | AJ Gordon责编 | Carol头图 | CSDN 付费下载于视觉中国出品 | CSDN云计算(ID:CSDNcloud)【CSDN如何构建一个交互式数据分析 Web 应用?】本文主要介绍如何利用Python的Streamlit库和Heroku云平台来做一个交互式数据分析Web应用 。 开发环境如下:

  • Windows10系统
  • Anaconda3(python3.7.4)
  • Git(2.26.0.windows.1)
  • Heroku账号
  • 梯子(Heroku需科学上网才可访问)

Streamlit
根据Streamlit官方文档介绍 , 它是一个开放源代码的Python库 , 可以轻松地为机器学习和数据科学构建漂亮的自定义web应用程序 。 也就是说 , 即使你对web开发并不熟悉 , 但只要利用它 , 就可以很容易搭建出一个Web 。
通过“pip install streamlit”进行安装 , 再执行“streamlit hello” 。 若安装成功 , 默认浏览器会自动打开或输入“localhost:8501” , 会弹出如下图界面 。
CSDN如何构建一个交互式数据分析 Web 应用?
本文插图
图1 安装成功界面Streamlit用于数据可视化的话 , 主要模块有:Cache , Interactive widgets , Charts 。
1) CacheStreamlit遵循由上至下的运行顺序 , 所以每次代码中有进行任何更改 , 都会重新开始运行一遍 , 会十分耗时 。 @st.cache会对封装起来的函数进行缓存 , 避免二次加载 。 如果函数中的代码发生变动 , cache会重新加载一遍并缓存起来 。 假如将代码还原到上一次版本 , 由于先前的数据已经缓存起来了 , 所以不会进行二次加载 。
import streamlit as stimport timest.write("Loading....")start_time = time.clock@st.cachedef expensive_computation(a, b): time.sleep(5) return a ** ba = 2b = 21res = expensive_computation(a, b)st.write("Result:", res)end_time = time.clockst.write("耗时:%0.1f 秒" % (end_time-start_time))
CSDN如何构建一个交互式数据分析 Web 应用?
本文插图
图2 Cache
2) Interactive widgetsStreamlit提供多种组件 , 如滑块 , 选择框和按钮等交互组件 。 利用组件可以灵活地展示数据 , 这一点类似很多BI工具提供的功能 。
import streamlit as stimport pandas as pdimport time# 按钮st.subheader("按钮")if st.button('Say hello'): st.write('Why hello there')# 复选框st.subheader("复选框")agree = st.checkbox('I agree')if agree: st.write('Great!')# 单选框st.subheader("单选框")genre = st.radio( "What's your favorite movie genre", ('Comedy', 'Drama', 'Documentary'))if genre == 'Comedy': st.write('You selected comedy.')else: st.write("You didn't select comedy.")# 选择框st.subheader("选择框")option = st.selectbox( 'How would you like to be contacted?', ('Email', 'Home phone', 'Mobile phone'))st.write('You selected:', option)# 多选框st.subheader("多选框")options = st.multiselect( 'What are your favorite colors',('Green', 'Yellow', 'Red', 'Blue'),'Yellow')st.write('You selected:', options)# 滑块st.subheader("滑块")age = st.slider('How old are you?', 0, 130, 25)st.write("I'm ", age, 'years old')# 数值输入框st.subheader("数值输入框")number = st.number_input('Insert a number')st.write('The current number is ', number)# 加载数据uploaded_file = st.file_uploader("Choose a CSV file", type="csv")if uploaded_file is not None: data = http://news.hoteastday.com/a/pd.read_csv(uploaded_file) st.write(data)# 进度条my_bar = st.progress(0)for percent_complete in range(100): time.sleep(0.1) my_bar.progress(percent_complete + 1)


推荐阅读