Some static definitions of the colour scale and the number format.

And the core implementation:

ndarray_html[source]

ndarray_html(a)

Example usages

A numeric 2D array:

ndarray_html(np.diag(np.ones(10)))

A numeric 1D array:

ndarray_html(np.ones((10,)))

A numeric 4D array:

ndarray_html(np.random.rand(2, 3, 4, 5))

When an ndarray has more than two dimensions, a text field (an ipywidget) is depicted on top of the table, where the user can slice down the array to have two dimension, so that it can be displayed in a table.

Note: The ipywidget that is used for multi-dimensional arrays is not correctly rendered in the documentation. Therefore see this screenshot:

A string array:

ndarray_html(np.diag(['nd', 'pretty', 'ndpretty']))

A bool array:

ndarray_html(np.array([True, False, True]))

Automatic default slicing

When an array would generally be too huge to display, it is automatically downsliced to the value of default_max_dim_size.

print(f"default_max_dim_size is {default_max_dim_size}")
ndarray_html(np.random.rand(10000, 1000))
default_max_dim_size is 200

Registering formatters for IPython

We don't always want to call ndarray_html to show our nice table. In order to make it the default formatter for cell return values, here are some helper functions to automatically register the formatters.

This makes use of IPyhton third-party formatters.

register_formatter[source]

register_formatter(dtype, html_formatter, print_formatter=None)

for ndarray

ndarray_stats_print_formatter[source]

ndarray_stats_print_formatter(x, _, __)

no_print_formatter[source]

no_print_formatter(x, _, __)

register_ndarray_formatter[source]

register_ndarray_formatter(print_formatter=ndarray_stats_print_formatter)

A formatter can be registered like this:

register_ndarray_formatter()

From then onwards, all returned ndarrays are formatted using ndpretty.

np.random.rand(2, 8)
2×8 float64 ndarray

for torch.Tensor

We also define a default formatter for PyTorch Tensors:

torch_tensor_html[source]

torch_tensor_html(t)

tensor_stats_print_formatter[source]

tensor_stats_print_formatter(x, _, __)

register_torch_tensor_formatter[source]

register_torch_tensor_formatter(print_formatter=tensor_stats_print_formatter)

if 'torch' in modules:
    register_torch_tensor_formatter()
    t = torch.Tensor(np.random.rand(10, 4))
else:
    t = 'torch not imported'
t
'torch not imported'

Default configuration for convenience

Finally we define a convenience function to quickly initialise the default configuration where both ndarrays and PyTorch tensors are formatted.

default[source]

default()

default()

TODOs and potential new features

  • [x] zero-dim arrays
  • [x] strings
  • [x] ints
  • [x] bools
  • [x] size limit: if array is larger than certain size, do auto-slicing
  • [ ] slider for decimal places or text field for format
  • [ ] fallback in case of exception
  • [ ] unregister hook
  • [ ] check if in IPython and don't crash otherwise