4

I want to set the precision for floats when using Colab Data Table Display

I'm finding that the code below works as intended in the native pandas dataframe display, but it does not work for the otherwise snazzier Data Table display.

import pandas as pd
df = pd.DataFrame(np.random.rand(15, 4), columns=list('ABCD'))

df.style.format("{:.2%}")

or alternatively for the last line above

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

The Colab demo for this feature also displays floats with ugly levels of precision, but I am hoping there's a way to control formatting. Any guidance greatly appreciated.

KC Bici
  • 41
  • 1
  • 2
  • Does this help you? https://stackoverflow.com/questions/43217916/pandas-data-precision – cs95 Jan 04 '20 at 06:07
  • @cs95, thanks though I'm finding that the formatting syntax there doesn't get respected in the Colab custom data table display. I'm trying to find out why that's the case and if there's a way around it. – KC Bici Jan 04 '20 at 06:13
  • The source code may contain useful info. https://github.com/googlecolab/colabtools/blob/master/google/colab/data_table.py – korakot Jan 04 '20 at 14:37

1 Answers1

2

Colab Data Table seems to only respect the data itself and not the formatting. It converts everything into JavaScript and uses another library to display the data.

When converting the data, it supports custom formatters. However, they can't be provided to a data table instance. Still, google.colab.datatable holds a dictionary of default formatters which you can monkey-patch:

from google.colab import data_table

data_table._DEFAULT_FORMATTERS[float] = lambda x: f"{x:.2f}"

Note this will change the behavior for all the displayed data tables.

bryant1410
  • 5,540
  • 4
  • 39
  • 40