我有多个数据帧想要显示在我的Dash应用程序上. 它们都经历了类似的格式化,所以我想在一个单独的函数中进行仪表表格式化,我向该函数输入要设置样式的数据帧.我在下面try 过了,但在我的仪表盘服务器上出现"加载布局错误"

import dash
from dash import html, dash_table
import pandas as pd

def styletable(dataframe):
    # Create a copy of the original DataFrame to avoid modifying it directly
    styled_df = dataframe.copy()

    COLNAMES = styled_df.columns
    indexName = styled_df.reindex().columns[0]

    # Convert the styled DataFrame to a Dash DataTable
    styled_table = dash_table.DataTable(
        columns=[{'name': indexName, 'id': indexName}] + [{'name': col, 'id': col, 'type': 'numeric'} for col in COLNAMES],
        data=styled_df,
        style_data_conditional=[
            {
                'if': {'column_id': col, 'filter_query': f'{{col}} < 0'},
                'color': 'red'
            }
            for col in styled_df.columns
        ],
        style_header={'fontWeight': 'bold'}
    )
    print(styled_table)
    return styled_table


app = dash.Dash()

df = pd.DataFrame({
    'Name': ['John Doe', 'Jane Doe', 'Mary Smith', 'Peter Jones'],
    'Age': [30, 25, 40, 35],
    'Salary': [50000, 40000, 60000, 55000]
})

styled_table = styletable(df)

app.layout = html.Div([styled_table])

if __name__ == '__main__':
    app.run_server(debug=True)

推荐答案

您的数据帧必须转换为具有to_dict('records')的DICT

def styletable(dataframe):
    # Create a copy of the original DataFrame to avoid modifying it directly
    styled_df = dataframe.copy()

    COLNAMES = styled_df.columns
    indexName = styled_df.reindex().columns[0]

    # Convert the styled DataFrame to a Dash DataTable
    styled_table = dash_table.DataTable(
        columns=[{'name': indexName, 'id': indexName}] + [{'name': col, 'id': col, 'type': 'numeric'} for col in COLNAMES],
        data=styled_df.to_dict('records'),
        style_data_conditional=[
            {
                'if': {'column_id': col, 'filter_query': f'{{col}} < 0'},
                'color': 'red'
            }
            for col in styled_df.columns
        ],
        style_header={'fontWeight': 'bold'}
    )
    print(styled_table)
    return styled_table

Python相关问答推荐

为什么自定义pytree aux_data对于jnp.数组来说在.jit()之后跟踪,而对于np.数组来说则不是?

Python-Polars:如何用两个值的平均值填充NA?

只需使用Python在图像中保留 colored颜色 范围区域

Tokenizer Docker:无法为Tokenizer构建轮子,这是安装pyproject.toml项目所需的

try 使用tensorFlow.keras.models时optree Import错误

使用decorator 自动继承父类

云上Gunicorn的Flask-socketIO无法工作

如何观察cv2.erode()的中间过程?

如何在Python中使用ijson解析SON期间检索文件位置?

使用GEKKO在简单DTE系统中进行一致初始化

返回nxon矩阵的diag元素,而不使用for循环

更改matplotlib彩色条的字体并勾选标签?

使用FASTCGI在IIS上运行Django频道

根据另一列中的nan重置值后重新加权Pandas列

带条件计算最小值

我如何使法国在 map 中完全透明的代码?

无法使用DBFS File API路径附加到CSV In Datricks(OSError Errno 95操作不支持)

在pandas中使用group_by,但有条件

在www.example.com中使用`package_data`包含不包含__init__. py的非Python文件

如何在海上配对图中使某些标记周围的黑色边框