Skip to content
forked from pydata/xarray

Commit

Permalink
Allow creating DataArrays with nD coordinate variables
Browse files Browse the repository at this point in the history
Closes pydata#2233
Closes pydata#8106
  • Loading branch information
dcherian committed Aug 31, 2023
1 parent 83c2919 commit 41647b5
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
9 changes: 1 addition & 8 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,21 +119,14 @@ 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}: "
f"length {sizes[d]} on the data but length {s} on "
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
Expand Down
20 changes: 20 additions & 0 deletions xarray/tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 41647b5

Please sign in to comment.