pydata / pydata/xarray

Setting datarrays with non-dimension coordinates errors

Open
#8,028 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

design question topic-error reporting topic-indexing
Dominant language
Python
Stars
4.2k
Forks
1.4k
Avg merge
2d 15h
Merged PRs (30d)
14

Description

What happened?

I'm not sure if this is a bug or a feature but I was expecting this example to work since the new coord is just a slight rewrite of the original dimension coordinate:

import xarray as xr

ds = xr.tutorial.open_dataset("air_temperature")

# Change the first time value:
ds["air_new"] = ds.air.copy()
air_new_changed = ds.air_new[{"time": 0}] * 3
ds.air_new.loc[air_new_changed.coords] = air_new_changed  # Works! :)

# Add a another coord along time axis and change 
# the first time value:
ds["air_new"] = ds.air.copy().assign_coords(
    {"time_float": ds.time.astype(float)}
)
air_new_changed = ds.air_new[{"time": 0}] * 4
ds.air_new.loc[air_new_changed.coords] = air_new_changed  # Error! :(

Traceback (most recent call last):

  Cell In[25], line 5
    ds.air_new.loc[air_new_changed.coords] = air_new_changed

  File ~\AppData\Local\mambaforge\envs\jw\lib\site-packages\xarray\core\dataarray.py:222 in __setitem__
    dim_indexers = map_index_queries(self.data_array, key).dim_indexers

  File ~\AppData\Local\mambaforge\envs\jw\lib\site-packages\xarray\core\indexing.py:182 in map_index_queries
    grouped_indexers = group_indexers_by_index(obj, indexers, options)

  File ~\AppData\Local\mambaforge\envs\jw\lib\site-packages\xarray\core\indexing.py:144 in group_indexers_by_index
    raise KeyError(f"no index found for coordinate {key!r}")

KeyError: "no index found for coordinate 'time_float'"

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

Run the provided Python example with xarray to reproduce the KeyError. Start at DataArray.setitem and the indexing.py paths shown in the traceback, then verify that assignment using a non-dimension coordinate either works as expected or has its behavior clearly defined and tested.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
data
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.