Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

preserve original dimension, coordinate and variable order in concat #4419

Merged
merged 9 commits into from
Sep 19, 2020
3 changes: 3 additions & 0 deletions xarray/core/concat.py
Original file line number Diff line number Diff line change
@@ -459,6 +459,9 @@ def ensure_common_dims(vars):
combined = concat_vars(vars, dim, positions)
assert isinstance(combined, Variable)
result_vars[k] = combined
elif k in result_vars:
# preserves original variable order
result_vars[k] = result_vars.pop(k)
kmuehlbauer marked this conversation as resolved.
Show resolved Hide resolved

result = Dataset(result_vars, attrs=result_attrs)
absent_coord_names = coord_names - set(result.variables)
33 changes: 33 additions & 0 deletions xarray/tests/test_concat.py
Original file line number Diff line number Diff line change
@@ -558,3 +558,36 @@ def test_concat_merge_single_non_dim_coord():
for coords in ["different", "all"]:
with raises_regex(ValueError, "'y' not present in all datasets"):
concat([da1, da2, da3], dim="x")


def test_concat_preserve_coordinate_order():
x = np.arange(0, 5)
y = np.arange(0, 10)
time = [0, 1]
data = np.zeros((2, 10, 5), dtype=bool)

ds1 = Dataset(
{"data": (["time", "y", "x"], [data[0]])},
coords={"time": (["time"], [time[0]]), "y": (["y"], y), "x": (["x"], x)},
)
ds2 = Dataset(
{"data": (["time", "y", "x"], [data[1]])},
coords={"time": (["time"], [time[1]]), "y": (["y"], y), "x": (["x"], x)},
)

expected = Dataset(
{"data": (["time", "y", "x"], data)},
coords={"time": (["time"], time), "y": (["y"], y), "x": (["x"], x)},
)
dcherian marked this conversation as resolved.
Show resolved Hide resolved

actual = concat([ds1, ds2], dim="time")

# check dimension order
for act, exp in zip(actual.dims, expected.dims):
assert act == exp
assert actual.dims[act] == expected.dims[exp]

# check coordinate order
for act, exp in zip(actual.coords, expected.coords):
assert act == exp
assert_identical(actual.coords[act], expected.coords[exp])