如何在 Dash DataTable 中的列上设置百分比格式?

问题描述 投票:0回答:1

我正在使用 Python Dash,我正在使用 DataTable 来显示来自某个数据集的一些信息。该数据集只有两列对应于教育率。费率是一个代表百分比的小数;但是,我尝试将百分比格式应用于列,但没有成功。事情是这样安排的:

percentage=FormatTemplate.percentage(2)

dash_table.DataTable(
                    id='educ-table',
                    columns=[{'name':i, 'id':i, 'type':'numeric', 'format':percentage } for i in df_edu[(df_edu['County']==df_edu['County'].unique()[0]) &(df_edu['Age']==df_edu['Age'].unique()[0])&(df_edu['Year']==df_edu['Year'].unique()[0])][['Educational Attainment', 'Percentage']].columns],
                    data=df_edu[(df_edu['County']==df_edu['County'].unique()[0]) &(df_edu['Age']==df_edu['Age'].unique()[0])&(df_edu['Year']==df_edu['Year'].unique()[0])][['Educational Attainment', 'Percentage']].to_dict('records'),
                    editable=True,
                    sort_action='native',
                    sort_mode='multi',
                    row_selectable=False,
                    row_deletable=False,
                    selected_columns=[],
                    selected_rows=[],
                    page_size=10,
                    style_cell={'font-family':'Arial', 'textAlign':'center'},
                    style_header={'font-family':'Arial'}
                )

当我加载应用程序时,我看到该列只应用了百分比格式一秒钟,然后又恢复为十进制。这是表格的截图:

python datatables plotly-dash
1个回答
0
投票

您的代码片段不是很有帮助,因为它又长又令人困惑。更重要的是,我们不知道你的 DataFrame 中百分比列的

dtype

假设您正在查看 Dash 文档 (https://dash.plotly.com/datatable/data-formatting) 中的数字格式页面并复制代码示例,我怀疑您列的数据类型是

string
(即
object
),而不是它应该的
float
。您可以使用以下代码进行检查:

df.dtypes

如果您看到列的 dtype 为

object
,则可以在将数据传递到 DataTable 之前使用以下代码段将数据重铸为
float

df["Percentage"] = df["Percentage"].astype(float)
© www.soinside.com 2019 - 2024. All rights reserved.