From bf78f2c36460b6537914d098161e0be233d6ea27 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Fri, 11 Apr 2025 15:28:01 -0700 Subject: [PATCH 1/2] BUG: Fix display with nested arrays Currently, the following will fail to display: ```python import xarray as xr import numpy as np x = np.empty((2, 2), dtype=object) for i in range(2): for j in range(2): x[i, j] = np.zeros(2) # Set to 1D array of size 2 ds = xr.DataArray(x) ds ``` Whenever there are `size==1` arrays, it currently does work: ```python import xarray as xr import numpy as np x = np.empty((2, 2), dtype=object) for i in range(2): for j in range(2): x[i, j] = np.zeros((1, 1, 1)) # Set to 3D array of size 1 ds = xr.DataArray(x) ds For context, I am running into this issue in https://github.com/pipefunc/pipefunc where one can put the resulting objects into `xarray.Dataset`s. For example, see the docs here https://pipefunc.readthedocs.io/en/latest/examples/physics-simulation/ (search for `xarray.Dataset`). --- xarray/core/formatting.py | 2 +- xarray/tests/test_formatting.py | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/xarray/core/formatting.py b/xarray/core/formatting.py index 993cddf2b57..7088bd40a06 100644 --- a/xarray/core/formatting.py +++ b/xarray/core/formatting.py @@ -184,7 +184,7 @@ def format_item(x, timedelta_format=None, quote_strings=True): if hasattr(x, "dtype"): x = x.item() return repr(x) if quote_strings else x - elif hasattr(x, "dtype") and np.issubdtype(x.dtype, np.floating): + elif hasattr(x, "dtype") and np.issubdtype(x.dtype, np.floating) and x.size == 1: return f"{x.item():.4}" else: return str(x) diff --git a/xarray/tests/test_formatting.py b/xarray/tests/test_formatting.py index 2e0925c1b9a..a9c6852173e 100644 --- a/xarray/tests/test_formatting.py +++ b/xarray/tests/test_formatting.py @@ -101,6 +101,8 @@ def test_format_item(self) -> None: (np.float16(1.1234), "1.123"), (np.float32(1.0111111), "1.011"), (np.float64(22.222222), "22.22"), + (np.zeros((1, 1)), "0.0"), + (np.zeros(2), "[0. 0.]"), ] for item, expected in cases: actual = formatting.format_item(item) From 4fef1ba84365c63f16d740c13b37b66111069c3a Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Fri, 11 Apr 2025 15:41:05 -0700 Subject: [PATCH 2/2] Add additional test case --- xarray/tests/test_formatting.py | 1 + 1 file changed, 1 insertion(+) diff --git a/xarray/tests/test_formatting.py b/xarray/tests/test_formatting.py index a9c6852173e..dce1528c7ae 100644 --- a/xarray/tests/test_formatting.py +++ b/xarray/tests/test_formatting.py @@ -103,6 +103,7 @@ def test_format_item(self) -> None: (np.float64(22.222222), "22.22"), (np.zeros((1, 1)), "0.0"), (np.zeros(2), "[0. 0.]"), + (np.zeros((2, 2)), "[[0. 0.]\n [0. 0.]]"), ] for item, expected in cases: actual = formatting.format_item(item)