Reputation: 41
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.
Upvotes: 4
Views: 6592
Reputation: 6340
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.
Upvotes: 2