【问题标题】:How to round decimal places in a Dash Table如何在 Dash Table 中舍入小数位
【发布时间】:2020-01-02 07:48:06
【问题描述】:

我有以下 python 代码:

import dash
import dash_html_components as html
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/dougmellon/rockies_dash/master/rockies_2019.csv')

def generate_table(dataframe, max_rows=10):
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +

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


external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[
    html.H4('Batting Stats (2019)'),
    generate_table(df)
])

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

正在从此 csv 文件 (github) 中提取数据:

当我运行以下代码时,

python app.py

它显示多于三位小数的数据 - 这不在我的 csv 文件中。

我已经尝试了三四次手动重新输入数据并将 CSV 重新上传到 github,但由于某种原因,仍然存在大于三位小数的数据。

有人对我如何解决这个问题有任何建议吗?

【问题讨论】:

    标签: python plotly-dash


    【解决方案1】:

    您需要在 Dash DataTable 构造函数的 columns 参数中传递每列的类型和格式说明符

    DataTable(..., columns=[{'id': 'one', 'type':'numeric', 'format': {'specifier': '.2f'}}])
    

    【讨论】:

      【解决方案2】:

      我会检查这个数据框,也许它可能会有所帮助 -

      How to display pandas DataFrame of floats using a format string for columns?

      或者干脆试试-

      pd.options.display.float_format = '${:.2f}'.format
      

      我刚刚在其中一个 DashTable 论坛中读到 - 您可以在 pandas 数据框中格式化数据,DataTable 将按原样显示它们。例如:

      显示百分比值:

      table_df['col_name']=table_df['col_name'].map('{:,.2f}%'.format)
      

      显示不带小数部分的浮点型:

      table_df['col_name']=table_df['col_name'].map("{:,.0f}".format)
      

      【讨论】:

      • 关于为什么要添加额外数字的任何想法?
      • 不确定,这里是讨论的链接 - community.plot.ly/t/dash-datatable-formatter-string/6328
      • 看,我发现了,但它适用于实际上具有更大小数并四舍五入到特定小数点的数据。出于某种原因,我的代码正在添加甚至不在我的数据集中的数字。我试图弄清楚如何。顺便感谢您的宝贵时间!
      • 几个月前我也遇到过类似的事情。我认为它添加数字的原因可能是因为它们已经存在。但是,您在脚本中的显示格式最初不会显示它们,原因与脚本中的显示格式有关。您可以通过更改原始脚本中的显示格式来检查它,看看是否出现了这些数字。
      • 有趣。这给了我一些尝试的东西。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多