如何舍入破折号中的小数位 Table

How to round decimal places in a Dash Table

我有以下 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 但由于某些原因仍然有大于三位小数的数据。

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

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

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)

您需要按照

行在 Dash DataTable 构造函数的 columns 参数中传递每列类型和格式说明符
DataTable(..., columns=[{'id': 'one', 'type':'numeric', 'format': {'specifier': '.2f'}}])

使用像 table_df['col_name']=table_df['col_name'].map('{:,.2f}%'.format) 这样的解决方案会将 dtype 从 floatint 更改为 str。使用 df 时可能会造成更多不便。例如做一些条件格式。 我建议使用 dash

中的原始文档

我将添加到 Dzamo Norton 解决方案。

您可以遍历列并为其分配特定的格式化程序

大概是这样

columns=[]
for col in df:
    if df[col].dtype == 'float64':
        item = dict(id=col, name=col, type='numeric', format=dict(specifier=',.2f'))  # Example result 47,359.02
        columns.append(item)
    else:
        item = dict(id=col, name=col)
        columns.append(item)