DataArray coordinates are dropped
Nobody has claimed this yet.
Assessment
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Newbie friendliness
- 48/100
Research direction
Start by running the provided Python reproduction and compare ds["var"].coords with ds.cf["cf_var_name"].coords. Inspect the ds.cf[...] DataArray selection path and verify that coordinates are retained so the shown CF plotting call resolves longitude and latitude successfully.
Written by the indexing model from the issue text.
Description
It looks like when I pull out a DataArray from a Dataset using cf_xarray the coordinates are dropped (while xarray keeps them).
Here is an example:
import xarray as xr
import cf_xarray
import numpy as np
x = 10
y = 20
ds = xr.Dataset(
dict(
lon=xr.DataArray(
np.arange(x), dims=("x"), attrs=dict(standard_name="longitude"),
),
lat=xr.DataArray(
np.arange(y), dims=("y"), attrs=dict(standard_name="latitude"),
),
var=xr.DataArray(
np.random.rand(x, y),
dims=("x", "y"),
attrs=dict(standard_name="cf_var_name"),
),
)
)
ds = ds.set_coords(["lon", "lat"])
ds.cf.describe()
Axes:
X: []
Y: []
Z: []
T: []
Coordinates:
longitude: ['lon']
latitude: ['lat']
vertical: []
time: []
Cell Measures:
area: unsupported
volume: unsupported
Standard Names:
cf_var_name: ['var']
print(ds["var"].coords)
Coordinates:
lon (x) int64 0 1 2 3 4 5 6 7 8 9
lat (y) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
print(ds.cf["cf_var_name"].coords)
Coordinates:
*empty*
# OK if I pull out the DataArray directly from ds
ds["var"].cf.plot(x="longitude", y="latitude")
<matplotlib.collections.QuadMesh at 0x7fbf13acf690>

# Problem if I pull out the DataArray from ds.cf
ds.cf["cf_var_name"].cf.plot(x="longitude", y="latitude")
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/noc/msm/scratch/climate/malmans/miniconda3/envs/overflows/lib/python3.7/site-packages/xarray/core/dataarray.py in _getitem_coord(self, key)
628 try:
--> 629 var = self._coords[key]
630 except KeyError:
KeyError: 'longitude'
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-7-072235ade112> in <module>
1 # Problem if I pull out the DataArray from ds.cf
----> 2 ds.cf["cf_var_name"].cf.plot(x="longitude", y="latitude")
/noc/msm/scratch/climate/malmans/miniconda3/envs/overflows/lib/python3.7/site-packages/cf_xarray/accessor.py in __call__(self, *args, **kwargs)
629 key_mappers=dict.fromkeys(self._keys, (_get_axis_coord_single,)),
630 )
--> 631 return self._plot_decorator(plot)(*args, **kwargs)
632
633 def __getattr__(self, attr):
/noc/msm/scratch/climate/malmans/miniconda3/envs/overflows/lib/python3.7/site-packages/cf_xarray/accessor.py in _plot_wrapper(*args, **kwargs)
597 xvar = self.accessor[kwargs["x"]]
598 else:
--> 599 xvar = self._obj[kwargs["x"]]
600 if "positive" in xvar.attrs:
601 if xvar.attrs["positive"] == "down":
/noc/msm/scratch/climate/malmans/miniconda3/envs/overflows/lib/python3.7/site-packages/xarray/core/dataarray.py in __getitem__(self, key)
638 def __getitem__(self, key: Any) -> "DataArray":
639 if isinstance(key, str):
--> 640 return self._getitem_coord(key)
641 else:
642 # xarray-style array indexing
/noc/msm/scratch/climate/malmans/miniconda3/envs/overflows/lib/python3.7/site-packages/xarray/core/dataarray.py in _getitem_coord(self, key)
631 dim_sizes = dict(zip(self.dims, self.shape))
632 _, key, var = _get_virtual_variable(
--> 633 self._coords, key, self._level_coords, dim_sizes
634 )
635
/noc/msm/scratch/climate/malmans/miniconda3/envs/overflows/lib/python3.7/site-packages/xarray/core/dataset.py in _get_virtual_variable(variables, key, level_vars, dim_sizes)
169 ref_var = dim_var.to_index_variable().get_level_variable(ref_name)
170 else:
--> 171 ref_var = variables[ref_name]
172
173 if var_name is None:
KeyError: 'longitude'
PS: This package is great! Let me know if I can help!
- Dominant language
- Python
- Stars
- 181
- Forks
- 49
- Avg merge
- 43m
- Merged PRs (30d)
- 1
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from xarray-contrib/cf-xarray
-
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
xarray-contrib/cf-xarray#623 ·
-
Consider adding opt-in support for circular axes when calling `bounds_to_vertices` (related to #594) Open
Difficulty 5/5 Over a week Newbie friendliness 38/100
xarray-contrib/cf-xarray#596 · 1 comment ·
-
Difficulty 3/5 1-2 days Newbie friendliness 25/100
xarray-contrib/cf-xarray#570 ·
-
Difficulty 4/5 3-5 days Newbie friendliness 15/100
xarray-contrib/cf-xarray#568 ·
-
Difficulty 3/5 1-2 days Newbie friendliness 35/100
xarray-contrib/cf-xarray#566 · 2 comments ·
All issues in xarray-contrib/cf-xarray
Similar issues
-
area/auth bug comp/agent P3 platform/discord type/security
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
NousResearch/hermes-agent#117848 ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
bancolombia/sentinel#23 ·
-
test md OpenCI
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
-
integration:quickjs org:external priority:backlog topic:code-interpreter topic:middleware type:feature
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
langchain-ai/deepagents#6450 ·
-
bug client
Difficulty 2/5 1-3 hours Newbie friendliness 88/100