8

I have the following python code:

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)

which is pulling data from this csv file (github):

enter image description here

When I run the following code,

python app.py

It displays data with greater than three decimals - which isn't in my csv file.

enter image description here

I have tried three or four times to reenter the data manually and re-upload the CSV to github but for some reason there is still data with greater than three decimals.

Does anyone have any suggestions as to how I could possibly fix this issue?

DougM
  • 920
  • 1
  • 9
  • 21

3 Answers3

8

You need to pass per-column type and format specifiers in the columns argument of the Dash DataTable constructor along the lines of

DataTable(..., columns=[{'id': 'one', 'type':'numeric', 'format': {'specifier': '.2f'}}])
Dzamo Norton
  • 1,194
  • 11
  • 17
6

I would check this for the dataframe and maybe it might help -

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

or simply try-

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

I just read in one of the DashTable forums that - you can format data in pandas dataframe and DataTable will display them that way as they are. For example:

To display percent value:

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

To display float type without decimal part:

table_df['col_name']=table_df['col_name'].map("{:,.0f}".format)
E. Gertz
  • 241
  • 4
  • 13
  • Any ideas as to why the additional numbers are being added? – DougM Jan 02 '20 at 07:56
  • Not sure, here is the link to the discussion - https://community.plot.ly/t/dash-datatable-formatter-string/6328 – E. Gertz Jan 02 '20 at 07:56
  • See, I found that but it's for data that actually has greater decimals and rounding to a specific decimal spot. For some reason my code is adding numbers that are not even in my data set. I'm trying to figure out how. Thanks for the time by the way! – DougM Jan 02 '20 at 07:59
  • I had something like that happen to me few months ago. I think that the reason it adds numbers is maybe because they are already present. However, your display format in the script don`t display them originally for reason that has to do with the display formatting in the script. You can check it by changing display formats in your original script and see if those numbers appear. – E. Gertz Jan 02 '20 at 08:00
  • Interesting. That gives me some things to try. Thank you. – DougM Jan 02 '20 at 08:01
  • Not yet. I am taking a break from it for a bit to see if I am just thinking too hard about it. – DougM Jan 02 '20 at 08:57
2

Using the solution like table_df['col_name']=table_df['col_name'].map('{:,.2f}%'.format) will change dtype from float or int to str. It might cause further inconvenience while working with the df. For example doing some conditional formatting. I would suggest to use original documentation from dash

I will add to Dzamo Norton solution.

You can loop through you columns and assign a specific formatter to it

Perhaps like this

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)
user16415140
  • 91
  • 1
  • 2