基于streamlit的数据产品开发-1

数据产品设计

本课程视频地址:
https://www.bilibili.com/video/BV1484y1E7Nm

  • 所谓数据产品。面向企业主要是用于决策支持,比如BI数据大屏;面向用户的,主要是一些基于数据服务。

  • 没有开发何谈设计,脱离产品开发谈设计是纸上谈兵。

  • 数据产品开发与实现工具:

    软件式: excel,帆软(findBI,finereport)

    开源的Python工具:smartchart(https://gitee.com/smartchart/smartchart); streamlit(https://streamlit.io/); gradio(https://www.gradio.app/)

  • 本门课程基于streamlit作为主要的开发python开发库

streamlit及其相关包的安装

  • 1,打开anconda powershell prompt
  • 2, 用入下命令:

pip install pyecharts -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host=mirrors.aliyun.com

分别安装streamlit pyecharts streamlit-echarts 三个库(用这几个库名替代掉上面命令中的pyecharts就行)

pyecharts(https://github.com/pyecharts/pyecharts)

streamlit-echarts(https://github.com/andfanilo/streamlit-echarts)

#安装完成后这些包应该就能正常导入了
import streamlit as st
from streamlit_echarts import st_echarts
from pyecharts import options as opts
from pyecharts.charts import Bar
from streamlit_echarts import st_pyecharts
import pandas as pd
2023-02-28 19:22:48.628 INFO    numexpr.utils: Note: NumExpr detected 12 cores but "NUMEXPR_MAX_THREADS" not set, so enforcing safe limit of 8.
2023-02-28 19:22:48.632 INFO    numexpr.utils: NumExpr defaulting to 8 threads.

第一个streamlit程序及其运行

以下内容多借鉴与官网文档:https://docs.streamlit.io/library/get-started/main-concepts

stream程序运行方法:

1,打开anconda powershell prompt

2, 用入下命令:streamlit run “文件完整路径.py” (注意这里目录在windows下暂时需要加引号)

#注意这里所有调用streamlit的代码不能直接在jupyter运行
st.write('Hello,World!')
#注意可以对代码修改,然后重新刷新就可以更新页面了,不用重新运行

st.write('Hello,World!1111111')
classwork 1

自己完成第一个程序的运行

数据的展示方法与方式

在 Streamlit 中有几种显示数据(表、数组、数据框)的方法: magic 和 st.write().其中st.write()是一个非常强大的函数,可用于写入从文本到表格的任何内容,未来我们将会进一步学习它。

magic 方法

可以在不调用任何 Streamlit 方法的情况下显示数据。这意味着您根本不必使用 st.write()!但是本质上是因为,每当 Streamlit 在程序里看到变量或文字值时,它都会使用 st.write() 自动将其展现。 有关详细信息,请参阅有关魔法命令的文档。

df = pd.DataFrame({
  'first column': [1, 2, 3, 4],
  'second column': [10, 20, 30, 40]
})

df
first columnsecond column
0110
1220
2330
3440

其他数据展示的方法

  • st.write()

st.write() 是 Streamlit 的“瑞士军刀”。 您几乎可以将任何内容传递给 st.write():文本、数据、Matplotlib 图形、Altair 图表等。

st.write("Here's our first attempt at using data to create a table:")
st.write(pd.DataFrame({
    'first column': [1, 2, 3, 4],
    'second column': [10, 20, 30, 40]
}))
  • st.dataframe

st.dataframe()能实现对数据更丰富的修饰

import numpy as np

dataframe = np.random.randn(10, 20)
st.dataframe(dataframe)
dataframe = pd.DataFrame(
    np.random.randn(10, 20),
    columns=('col %d' % i for i in range(20)))

st.dataframe(dataframe.style.highlight_max(axis=0))
  • st.table

当你需要非交互式静态表格时可能需要它

dataframe = pd.DataFrame(
    np.random.randn(10, 20),
    columns=('col %d' % i for i in range(20)))
st.table(dataframe)
classwork 2
  1. 导入男鞋数据,分别magic与st.write的方式显示前三行

  2. 显示男鞋数据中的price与itemid列,并让最大值高亮

  3. 用st.table静态显示前10行数据

#导入男鞋数据
a=pd.read_csv(r"D:\try\shoes.csv")
a.iloc[0:2]
_id.$oidinfo.上市年份季节info.上市时间info.产品名称info.低帮鞋品名info.功能info.吊牌价info.品牌info.图案info.场合...info.鞋面材质info.颜色分类info.风格itemidlocationnickpricesalestitleurl
05aa77041be9b0338dc1faab42018年春季NaNNaN商务休闲鞋轻质NaNYEARCON/意尔康纯色日常...头层牛皮(除牛反绒)黑色土黄商务562121114807浙江 丽水意尔康皮鞋旗舰店269.01583人付款意尔康男鞋2018春季新款英伦真皮商务休闲皮鞋青年男士皮鞋子男潮http://detail.tmall.com/item.htm?id=5621211148...
15aa77042be9b0338dc1faab52017年秋季NaNNaN商务休闲鞋轻质NaNYEARCON/意尔康纯色办公室...头层牛皮(除牛反绒)黑色棕色黑色加绒版棕色加绒版黑色镂空棕色镂空商务545941839337浙江 丽水意尔康皮鞋旗舰店199.01607人付款意尔康旗舰店官方店男鞋春秋真皮爸爸鞋中老年人商务休闲皮鞋子男http://detail.tmall.com/item.htm?id=5459418393...

2 rows × 52 columns


可视化图表的展示

Streamlit 默认支持多种流行的数据图表库,如 Matplotlib、Altair、deck.gl 等。如果需要echarts则需要额外安装streamlit-echarts库

streamlit 默认可视化方案

chart_data = pd.DataFrame(
     np.random.randn(20, 3),
     columns=['a', 'b', 'c'])

st.line_chart(chart_data)
map_data = pd.DataFrame(
    np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
    columns=['lat', 'lon'])

st.map(map_data)

echarts的可视化方案

https://github.com/andfanilo/streamlit-echarts

这也支持两种方法:

  • 基于pyecharts的方法

pyecharts 官网案例:https://gallery.pyecharts.org/

文档: https://pyecharts.org/

  • 原生的echarts方法,这种方法可能实现更多的功能

echarts 官网案例: https://echarts.apache.org/examples/zh/index.html

echarts 教程:https://www.w3cschool.cn/echarts_tutorial/

from pyecharts import options as opts
from pyecharts.charts import Bar
from streamlit_echarts import st_pyecharts

b = (
    Bar()
    .add_xaxis(["Microsoft", "Amazon", "IBM", "Oracle", "Google", "Alibaba"])
    .add_yaxis(
        "2017-2018 Revenue in (billion $)", [21.2, 20.4, 10.3, 6.08, 4, 2.2]
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title="Top cloud providers 2018", subtitle="2017-2018 Revenue"
        ),
        toolbox_opts=opts.ToolboxOpts(),
    )
)
st_pyecharts(b)
from streamlit_echarts import st_echarts

options = {
    "xAxis": {
        "type": "category",
        "data": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    "yAxis": {"type": "value"},
    "series": [
        {"data": [820, 932, 901, 934, 1290, 1330, 1320], "type": "line"}
    ],
}
st_echarts(options=options)
classwork3
a=pd.read_csv(r"D:\try\shoes.csv")
a.columns.tolist()
['_id.$oid',
 'info.上市年份季节',
 'info.上市时间',
 'info.产品名称',
 'info.低帮鞋品名',
 'info.功能',
 'info.吊牌价',
 'info.品牌',
 'info.图案',
 'info.场合',
 'info.外底材料',
 'info.季节',
 'info.尺码',
 'info.帮面内里材质',
 'info.帮面材质',
 'info.性别',
 'info.是否商场同款',
 'info.是否瑕疵',
 'info.款号',
 'info.款式',
 'info.流行元素',
 'info.真皮材质工艺',
 'info.细分风格',
 'info.货号',
 'info.跟底款式',
 'info.运动系列',
 'info.运动鞋科技',
 'info.适合路面',
 'info.适用对象',
 'info.销售渠道类型',
 'info.闭合方式',
 'info.靴子品名',
 'info.靴筒内里材质',
 'info.靴筒材质',
 'info.靴筒高度',
 'info.鞋制作工艺',
 'info.鞋垫材质',
 'info.鞋头款式',
 'info.鞋底材质',
 'info.鞋码',
 'info.鞋跟高',
 'info.鞋面内里材质',
 'info.鞋面材质',
 'info.颜色分类',
 'info.风格',
 'itemid',
 'location',
 'nick',
 'price',
 'sales',
 'title',
 'url']
a.groupby("info.鞋面材质").size()
info.鞋面材质
PU             671
二层牛皮(除牛反绒)     605
二层猪皮             8
人造革             80
塑胶              10
多种材质拼接          21
太空革              9
头层牛皮(除牛反绒)    3470
头层猪皮             6
布                8
棉布               1
牛仔布              2
牛反绒             12
磨砂皮             14
绒面              15
网布               7
羊皮毛一体            1
超纤              35
超纤皮              1
鳄鱼皮              4
dtype: int64

页面组件(Widgets)

交互式页面的实现是基于组件完成的,当你要与数据进行交互时也需要类似的组件

x = st.slider('x')#本质上实现了数据的传入
st.write(x, 'squared is', x * x)

可以在组件里通过定义key来传递变量

st.text_input("Your name", key="name")

# You can access the value at any point with:
st.session_state.name

通过组件的值来判断是否显示数据框

if st.checkbox('Show dataframe'):
    chart_data = pd.DataFrame(
       np.random.randn(20, 3),
       columns=['a', 'b', 'c'])

    chart_data

基于数据框来进行选择

df = pd.DataFrame({
    'first column': [1, 2, 3, 4],
    'second column': [10, 20, 30, 40]
    })

option = st.selectbox(
    'Which number do you like best?',
     df['first column'])

'You selected: ', option

classwork 4

1, 通过text_input传入男鞋数据的列名,然后输出对应列名类别的商品数量

2,通过selectbox实现上题的功能

页面的布局

  • Streamlit 可以使用 st.sidebar 在左侧面板侧边栏中轻松组织小部件。 传递给 st.sidebar 的每个元素都固定在左侧,允许用户专注于应用程序中的内容,同时仍然可以访问 UI 控件。

  • st.columns 允许您并排放置小部件

# Add a selectbox to the sidebar:
add_selectbox = st.sidebar.selectbox(
    'How would you like to be contacted?',
    ('Email', 'Home phone', 'Mobile phone')
)

# Add a slider to the sidebar:
add_slider = st.sidebar.slider(
    'Select a range of values',
    0.0, 100.0, (25.0, 75.0)
)
left_column, right_column = st.columns(2)
# You can use a column just like st.sidebar:
left_column.button('Press me!')

# Or even better, call Streamlit functions inside a "with" block:
with right_column:
    chosen = st.radio(
        'Sorting hat',
        ("Gryffindor", "Ravenclaw", "Hufflepuff", "Slytherin"))
    st.write(f"You are in {chosen} house!")
  • 布局组件与echarts的兼容问题

https://github.com/andfanilo/streamlit-echarts/issues/43

需要在程序开头加入如下代码:

并且所有echarts图片必须以函数的形式引入

#st.markdown(" <style>iframe{ height: 300px !important } ", unsafe_allow_html=True)
  • 如下代码是可以正常运行的
import streamlit as st
from streamlit_echarts import st_echarts
from pyecharts import options as opts
from pyecharts.charts import Bar
from streamlit_echarts import st_pyecharts
import pandas as pd
import numpy as np

#下面这行程序必须写入
st.markdown(" <style>iframe{ height: 300px !important } ", unsafe_allow_html=True)


a=pd.read_csv(r"D:\try\shoes.csv")

a_xm=a.groupby("info.鞋面材质").size()

def echart_shoes():
    return {
        "color":"red",
        "tooltip": {
          "trigger": 'axis',
          "axisPointer": {
            "type": 'shadow'
          }
        },
        "xAxis": {
            "type": "category",
            "data": a_xm.index.tolist(),
        },
        "yAxis": {"type": "value"},
        "series": [
            {"data": a_xm.values.tolist(), "type": "line"}
        ],
    }

def echarts_random_options():
    return {
        "xAxis": {"type": "category", "data": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]},
        "yAxis": {"type": "value"},
        "series": [
            {"data": list(np.random.random(size=7) * 800),
             "type": "line"}
        ],
    }

    
left_column, right_column = st.columns(2)

with left_column:
    st_echarts(options=echart_shoes())


with right_column:
    st_echarts(options=echarts_random_options())

classwork 5

  • 并列输出两个表格

  • 并列输出两个基于男鞋数据的统计可视化图


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值