Some static definitions of the colour scale and the number format.
And the core implementation:
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))
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.
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)
if 'torch' in modules:
register_torch_tensor_formatter()
t = torch.Tensor(np.random.rand(10, 4))
else:
t = 'torch not imported'
t
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