Skip to content

assign_coords with mixed DataArray / array args removes coords #3483

Description

@keewis

I'm not sure if using assign_coords to overwrite the data of coords is the best way to do so, but using mixed args (on current master) turns out to have surprising results:

>>> obj = xr.DataArray(
...     data=[6, 3, 4, 6],
...     coords={"x": list("abcd"), "y": ("x", range(4))},
...     dims="x",
... )
>>> obj
<xarray.DataArray 'obj' (x: 4)>
array([6, 3, 4, 6])
Coordinates:
  * x        (x) <U1 'a' 'b' 'c' 'd'
    y        (x) int64 0 1 2 3
>>> # works as expected
>>> obj.assign_coords(coords={"x": list("efgh"), "y": ("x", [0, 2, 4, 6])})
<xarray.DataArray 'obj' (x: 4)>
array([6, 3, 4, 6])
Coordinates:
  * x        (x) <U1 'e' 'f' 'g' 'h'
    y        (x) int64 0 2 4 6
>>> # works, too (same as .data / .values)
>>> obj.assign_coords(coords={
...     "x": obj.x.copy(data=list("efgh")).variable,
...     "y": ("x", [0, 2, 4, 6]),
... })
<xarray.DataArray 'obj' (x: 4)>
array([6, 3, 4, 6])
Coordinates:
  * x        (x) <U1 'e' 'f' 'g' 'h'
    y        (x) int64 0 2 4 6
>>> # this drops "y"
>>> obj.assign_coords(coords={
...     "x": obj.x.copy(data=list("efgh")),
...     "y": ("x", [0, 2, 4, 6]),
... })
<xarray.DataArray 'obj' (x: 4)>
array([6, 3, 4, 6])
Coordinates:
  * x        (x) <U1 'e' 'f' 'g' 'h'

Passing a DataArray for y, like obj.y * 2 while also changing x (the type does not matter) always results in a MergeError:

>>> obj.assign_coords(x=list("efgh"), y=obj.y * 2)
xarray.core.merge.MergeError: conflicting values for index 'x' on objects to be combined:
first value: Index(['e', 'f', 'g', 'h'], dtype='object', name='x')
second value: Index(['a', 'b', 'c', 'd'], dtype='object', name='x')

I would expect the result to be the same regardless of the type of the new coords.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions