pydata / pydata/xarray

assign_coords with mixed DataArray / array args removes coords

Open
#3,483 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
4.2k
Forks
1.4k
Avg merge
2d 15h
Merged PRs (30d)
14

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at DataArray.assign_coords and follow the handling of mixed DataArray, Variable, and array coordinate arguments into the merge path. Reproduce the examples from the issue, including the MergeError case, and verify that replacing x preserves y and that equivalent coordinate types produce the same result.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
data
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.