首页 > 解决方案 > Python Dash 如何创建两列表?

问题描述

我正在尝试为 Plotly Dash webapp 创建一个表。

根据数据框中的数据,我想创建下表(两列表,一侧的列名,另一侧的值):

列名 | 价值

我正在使用下面的逻辑,但它只是给了我一个包含一列的表,并将值和列名堆叠在同一列中。

  return html.Table(
        # Header
        [html.Tr([html.Tr(col) for col in dataframe.columns])] +

        # Body
        [html.Td([
            html.Tr(dataframe.iloc[i][col]) for col in dataframe.columns
        ]) for i in range(min(len(dataframe), max_rows))]
    )

对于那些熟悉 html 的人来说,这就是我想要做的:

<table>
<tr>
<td>Column Name:</td>
<td>Values:</td>
</tr>
</table>

@brokenfoot 我尝试使用您的示例,但它告诉我逗号是语法错误:

    return html.Table(
        [
            html.Tr( [html.Td(col) for col in dataframe.columns
           ,html.Td(dataframe.iloc[i][col]) for col in dataframe.columns])
            for i in range(min(len(dataframe), max_rows))
        ]
                     )

标签: pythonplotly-dash

解决方案


您可以通过以下方式传递标头数据:

html.Th()

和实际的表格数据:

html.Td()

示例用法:

 ... 
            html.Table(className='table',
                children = 
                [
                    html.Tr( [html.Th('Attribute'), html.Th("Value")] )
                ] +
                [
                    html.Tr( [html.Td('OS'),         html.Td('{}'.format(get_platform()))] ),
                    html.Tr( [html.Td('#CPUs'),      html.Td('{}'.format(ps.cpu_count()))] ),
                    html.Tr( [html.Td('CPU Clock'),  html.Td('{} MHz'.format(int(ps.cpu_freq().current)))] ),
                    html.Tr( [html.Td('RAM'),       html.Td('{} GB'.format(ps.virtual_memory().total >> 30))] ),
                    html.Tr( [html.Td('#processes'), html.Td('{}'.format(len(ps.pids())))] ),
                ]
            ),
. . .

您可以签出以下文件以获取 html 表格、图表用法:
https ://github.com/tarun27sh/dash-on-heroku/blob/master/app.py

编辑: 您可以尝试(未经测试!):

html.Table(className='table',
    children = 
    [
        html.Tr( [html.Th(col) for col in dataframe.columns] )
    ] +
    [
        for i in range(min(len(dataframe), max_rows)):
            html.Tr( [html.Td('{}' .format(dataframe.iloc[i][col])) for col in dataframe.columns])
    ]
),

推荐阅读