From 41647b5d25f17e414634ac6af7103d52d213914b Mon Sep 17 00:00:00 2001 From: dcherian Date: Thu, 31 Aug 2023 10:06:06 +0530 Subject: [PATCH] Allow creating DataArrays with nD coordinate variables Closes #2233 Closes #8106 --- xarray/core/dataarray.py | 9 +-------- xarray/tests/test_dataarray.py | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py index df57ad898e4..a789784fa4f 100644 --- a/xarray/core/dataarray.py +++ b/xarray/core/dataarray.py @@ -119,7 +119,7 @@ def _check_coords_dims(shape, coords, dims): f"dimensions {dims}" ) - for d, s in zip(v.dims, v.shape): + for d, s in v.sizes.items(): if s != sizes[d]: raise ValueError( f"conflicting sizes for dimension {d!r}: " @@ -127,13 +127,6 @@ def _check_coords_dims(shape, coords, dims): f"coordinate {k!r}" ) - if k in sizes and v.shape != (sizes[k],): - raise ValueError( - f"coordinate {k!r} is a DataArray dimension, but " - f"it has shape {v.shape!r} rather than expected shape {sizes[k]!r} " - "matching the dimension size" - ) - def _infer_coords_and_dims( shape, coords, dims diff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py index 183c0ad7371..f7ab648a868 100644 --- a/xarray/tests/test_dataarray.py +++ b/xarray/tests/test_dataarray.py @@ -7073,3 +7073,23 @@ def test_error_on_ellipsis_without_list(self) -> None: da = DataArray([[1, 2], [1, 2]], dims=("x", "y")) with pytest.raises(ValueError): da.stack(flat=...) # type: ignore + + +def test_nD_coord_dataarray(): + # should succeed + da = DataArray( + np.ones((2, 4)), + dims=("x", "y"), + coords={ + "x": (("x", "y"), np.arange(8).reshape((2, 4))), + "y": ("y", np.arange(4)), + }, + ) + da2 = DataArray(np.ones(4), dims=("y"), coords={"y": ("y", np.arange(4))}) + + _, actual = xr.align(da, da2) + assert_identical(da2, actual) + + expected = da.drop_vars("x") + _, actual = xr.broadcast(da, da2) + assert_identical(expected, actual)