Python应用开发——30天学习Streamlit Python包进行APP的构建(7)

st.data_editor

显示数据编辑器 widget。

数据编辑器 widget 可让你在类似表格的用户界面中编辑数据框和许多其他数据结构。

警告

When going from st.experimental_data_editor to st.data_editor in 1.23.0, the data editor's representation in st.session_state was changed. The edited_cells dictionary is now called edited_rows and uses a different format ({0: {"column name": "edited value"}} instead of {"0:1": "edited value"}). You may need to adjust the code if your app uses st.experimental_data_editor in combination with st.session_state.

函数

Function signature[source]

st.data_editor(data, *, width=None, height=None, use_container_width=False, hide_index=None, column_order=None, column_config=None, num_rows="fixed", disabled=False, key=None, on_change=None, args=None, kwargs=None)

Returns

(pandas.DataFrame, pandas.Series, pyarrow.Table, numpy.ndarray, list, set, tuple, or dict.)

The edited data. The edited data is returned in its original data type if it corresponds to any of the supported return types. All other data types are returned as a pandas.DataFrame.

Parameters

data (pandas.DataFrame, pandas.Series, pandas.Styler, pandas.Index, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.DataFrame, list, set, tuple, dict, or None)

The data to edit in the data editor.

Note

  • Styles from pandas.Styler will only be applied to non-editable columns.
  • Mixing data types within a column can make the column uneditable.
  • Additionally, the following data types are not yet supported for editing: complex, list, tuple, bytes, bytearray, memoryview, dict, set, frozenset, fractions.Fraction, pandas.Interval, and pandas.Period.
  • To prevent overflow in JavaScript, columns containing datetime.timedelta and pandas.Timedelta values will default to uneditable but this can be changed through column configuration.

width (int or None)

Desired width of the data editor expressed in pixels. If width is None (default), Streamlit sets the data editor width to fit its contents up to the width of the parent container. If width is greater than the width of the parent container, Streamlit sets the data editor width to match the width of the parent container.

height (int or None)

Desired height of the data editor expressed in pixels. If height is None (default), Streamlit sets the height to show at most ten rows. Vertical scrolling within the data editor element is enabled when the height does not accomodate all rows.

use_container_width (bool)

Whether to override width with the width of the parent container. If use_container_width is False (default), Streamlit sets the data editor's width according to width. If use_container_width is True, Streamlit sets the width of the data editor to match the width of the parent container.

hide_index (bool or None)

Whether to hide the index column(s). If hide_index is None (default), the visibility of index columns is automatically determined based on the data.

column_order (Iterable of str or None)

Specifies the display order of columns. This also affects which columns are visible. For example, column_order=("col2", "col1") will display 'col2' first, followed by 'col1', and will hide all other non-index columns. If None (default), the order is inherited from the original data structure.

column_config (dict or None)

Configures how columns are displayed, e.g. their title, visibility, type, or format, as well as editing properties such as min/max value or step. This needs to be a dictionary where each key is a column name and the value is one of:

  • None to hide the column.
  • A string to set the display label of the column.
  • One of the column types defined under st.column_config, e.g. st.column_config.NumberColumn("Dollar values”, format=”$ %d") to show a column as dollar amounts. See more info on the available column types and config options here.

To configure the index column(s), use _index as the column name.

num_rows ("fixed" or "dynamic")

Specifies if the user can add and delete rows in the data editor. If "fixed", the user cannot add or delete rows. If "dynamic", the user can add and delete rows in the data editor, but column sorting is disabled. Defaults to "fixed".

disabled (bool or Iterable of str)

Controls the editing of columns. If True, editing is disabled for all columns. If an Iterable of column names is provided (e.g., disabled=("col1", "col2")), only the specified columns will be disabled for editing. If False (default), all columns that support editing are editable.

key (str)

An optional string to use as the unique key for this widget. If this is omitted, a key will be generated for the widget based on its content. Multiple widgets of the same type may not share the same key.

on_change (callable)

An optional callback invoked when this data_editor's value changes.

args (tuple)

An optional tuple of args to pass to the callback.

kwargs (dict)

An optional dict of kwargs to pass to the callback.

代码

这段代码使用了Streamlit和Pandas库。首先,创建了一个包含命令、评分和是否为小部件的数据框df。然后,使用st.data_editor()函数创建了一个交互式的数据编辑器,用户可以在编辑器中修改数据框。接着,代码找到评分最高的命令,并将其显示在屏幕上。

import streamlit as st
import pandas as pd

#数据中有4个参数,给到了三个不同的控件,并设定了期是否开启了空间
df = pd.DataFrame(
    [
       {"command": "st.selectbox", "rating": 4, "is_widget": True},
       {"command": "st.balloons", "rating": 5, "is_widget": False},
       {"command": "st.time_input", "rating": 3, "is_widget": True},
   ]
)
#将定义的数据格式传入编辑器
edited_df = st.data_editor(df)

#这个程序可以实现当你选择不同的控件,回给出不同的结果
favorite_command = edited_df.loc[edited_df["rating"].idxmax()]["command"]
st.markdown(f"Your favorite command is **{favorite_command}** 🎈")

通过将 num_rows 设置为 "动态",还可以允许用户添加和删除行: 

这段代码使用了Streamlit和Pandas库。首先,它创建了一个包含命令、评分和是否为小部件的数据框df。然后,使用st.data_editor函数创建了一个交互式数据编辑器,让用户可以编辑数据框。接着,代码找到评分最高的行,并提取该行的命令,最后使用st.markdown函数将用户最喜欢的命令显示在页面上。

import streamlit as st
import pandas as pd

df = pd.DataFrame(
    [
       {"command": "st.selectbox", "rating": 4, "is_widget": True},
       {"command": "st.balloons", "rating": 5, "is_widget": False},
       {"command": "st.time_input", "rating": 3, "is_widget": True},
   ]
)
edited_df = st.data_editor(df, num_rows="dynamic")

favorite_command = edited_df.loc[edited_df["rating"].idxmax()]["command"]
st.markdown(f"Your favorite command is **{favorite_command}** 🎈")

同样也可以用这 column_config, hide_index, column_order, or disabled: 

这段代码使用了Pandas和Streamlit库。首先,它创建了一个包含命令、评分和是否为小部件的数据框(DataFrame)。然后,使用Streamlit的data_editor函数编辑了数据框,对列进行了配置,设置了列的格式和范围,并禁用了某些列并隐藏了索引。接着,代码找到评分最高的命令,并输出了用户最喜爱的命令。

import pandas as pd
import streamlit as st

df = pd.DataFrame(
    [
        {"command": "st.selectbox", "rating": 4, "is_widget": True},
        {"command": "st.balloons", "rating": 5, "is_widget": False},
        {"command": "st.time_input", "rating": 3, "is_widget": True},
    ]
)
edited_df = st.data_editor(
    df,
    column_config={
        "command": "Streamlit Command",
        "rating": st.column_config.NumberColumn(
            "Your rating",
            help="How much do you like this command (1-5)?",
            min_value=1,
            max_value=5,
            step=1,
            format="%d ⭐",
        ),
        "is_widget": "Widget ?",
    },
    disabled=["command", "is_widget"],
    hide_index=True,
)

favorite_command = edited_df.loc[edited_df["rating"].idxmax()]["command"]
st.markdown(f"Your favorite command is **{favorite_command}** 🎈")

配置列

您可以通过列配置 API 配置 st.dataframe 和 st.data_editor 中列的显示和编辑行为。我们开发的 API 可让您在数据框架和数据编辑器列中添加图片、图表和可点击的 URL。此外,您还可以编辑单个列、将列设置为分类列并指定它们可以使用的选项、隐藏数据框的索引等。 

Column configuration

在 Streamlit 中处理数据时,st.column_config 类是配置数据显示和交互的强大工具。该类专为 st.dataframe 和 st.data_editor 中的 column_config 参数而设计,提供了一整套方法,可根据各种数据类型(从简单的文本和数字到列表、URL、图像等)定制列。

无论是将时间数据转换为用户友好的格式,还是利用图表和进度条实现更清晰的数据可视化,列配置不仅能为用户提供丰富的数据查看体验,还能确保您拥有各种工具,以您想要的方式展示数据并与之交互。

st.column_config.Column

在 st.dataframe 或 st.data_editor 中配置通用列。

列的类型将根据数据类型自动推断。该命令需要在 st.dataframe 或 st.data_editor 的 column_config 参数中使用。

要更改列的类型并启用特定类型的配置选项,请使用 st.column_config 命名空间中的一种列类型,例如 st.column_config.NumberColumn。

Function signature[source]

st.column_config.Column(label=None, *, width=None, help=None, disabled=None, required=None)

Parameters

label (str or None)

The label shown at the top of the column. If None (default), the column name is used.

width ("small", "medium", "large", or None)

The display width of the column. Can be one of "small", "medium", or "large". If None (default), the column will be sized to fit the cell contents.

help (str or None)

An optional tooltip that gets displayed when hovering over the column label.

disabled (bool or None)

Whether editing should be disabled for this column. Defaults to False.

required (bool or None)

  • 21
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

此星光明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值