当前位置: 首页 > news >正文

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 pddf = 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 stdf = 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)

相关文章:

  • Python实现逻辑回归与判别分析--西瓜数据集
  • BizDevOps全局建设思路:横向串联,纵向深化
  • Linux测试服务器端口是否打开
  • gitblit git pycharm 新建版本库及push备忘
  • 【linux】shell脚本中设置字体颜色,背景颜色详细攻略
  • HTTP/3 协议学习
  • 如何利用机器学习算法进行数据分析和挖掘,数据优化、预处理、特征提取等老板吩咐的工作
  • 自制HTML5游戏《开心消消乐》
  • Wireshark的基本用法以及注意事项
  • 速盾:高防服务器防御 DDoS 攻击的掩护技巧
  • 逆向学习网络篇:通过Socket建立连接并传输数据
  • 企业ERP系统规划图
  • 智慧公厕系统厂家的核心技术与光明源应用案例
  • 2020C++等级考试二级真题题解
  • oracle12c到19c adg搭建(五)dg搭建后进行切换19c进行数据字典升级
  • SegmentFault for Android 3.0 发布
  • JavaScript函数式编程(一)
  • Java精华积累:初学者都应该搞懂的问题
  • js递归,无限分级树形折叠菜单
  • js作用域和this的理解
  • Linux下的乱码问题
  • mockjs让前端开发独立于后端
  • mongo索引构建
  • PHP 小技巧
  • 彻底搞懂浏览器Event-loop
  • 从地狱到天堂,Node 回调向 async/await 转变
  • 前嗅ForeSpider教程:创建模板
  • 强力优化Rancher k8s中国区的使用体验
  • 通信类
  • 小而合理的前端理论:rscss和rsjs
  • 没有任何编程基础可以直接学习python语言吗?学会后能够做什么? ...
  • 如何用纯 CSS 创作一个菱形 loader 动画
  • 智能情侣枕Pillow Talk,倾听彼此的心跳
  • ​Redis 实现计数器和限速器的
  • # Pytorch 中可以直接调用的Loss Functions总结:
  • # 睡眠3秒_床上这样睡觉的人,睡眠质量多半不好
  • # 执行时间 统计mysql_一文说尽 MySQL 优化原理
  • $emit传递多个参数_PPC和MIPS指令集下二进制代码中函数参数个数的识别方法
  • (06)金属布线——为半导体注入生命的连接
  • (1/2) 为了理解 UWP 的启动流程,我从零开始创建了一个 UWP 程序
  • (Redis使用系列) Springboot 整合Redisson 实现分布式锁 七
  • (ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY)讲解
  • (机器学习的矩阵)(向量、矩阵与多元线性回归)
  • (几何:六边形面积)编写程序,提示用户输入六边形的边长,然后显示它的面积。
  • (介绍与使用)物联网NodeMCUESP8266(ESP-12F)连接新版onenet mqtt协议实现上传数据(温湿度)和下发指令(控制LED灯)
  • (论文阅读32/100)Flowing convnets for human pose estimation in videos
  • (一)RocketMQ初步认识
  • (转) Face-Resources
  • (转)EXC_BREAKPOINT僵尸错误
  • (转载)(官方)UE4--图像编程----着色器开发
  • ***监测系统的构建(chkrootkit )
  • .Net 4.0并行库实用性演练
  • .NET 4.0网络开发入门之旅-- 我在“网” 中央(下)
  • .NET C# 配置 Options
  • .NET C# 使用 SetWindowsHookEx 监听鼠标或键盘消息以及此方法的坑