-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Description
What happened?
Printing an empty slice of a DataArray with a RangeIndex coordinate raises an error.
What did you expect to happen?
No error.
Minimal Complete Verifiable Example
import numpy as np, xarray as xr, xarray.indexes
n = 30
step = 1
da = xr.DataArray(np.zeros(n), dims=["x"])
da = da.assign_coords(
xr.Coordinates.from_xindex(
xr.indexes.RangeIndex.linspace(0, (n - 1) * step, n, dim="x")))
sub = da.isel(x=slice(0))
print(sub)
MVCE confirmation
- Minimal example — the example is as focused as reasonably possible to demonstrate the underlying issue in xarray.
- Complete example — the example is self-contained, including all data and the text of any traceback.
- Verifiable example — the example copy & pastes into an IPython prompt or Binder notebook, returning the result.
- New issue — a search of GitHub Issues suggests this is not a duplicate.
- Recent environment — the issue occurs with the latest version of xarray and its dependencies.
Relevant log output
<elided traceback...>
File ~/.local/lib/python3.13/site-packages/xarray/indexes/range_index.py:299, in RangeIndex.step(self)
296 @property
297 def step(self) -> float:
298 """Returns the spacing between values."""
--> 299 return self.transform.step
File ~/.local/lib/python3.13/site-packages/xarray/indexes/range_index.py:57, in RangeCoordinateTransform.step(self)
55 @property
56 def step(self) -> float:
---> 57 return (self.stop - self.start) / self.size
ZeroDivisionError: float division by zero
Anything else we need to know?
At least, the print should not error. Ideally, accessing the .step
attribute of the coordinate would keep working and return the same step value as prior to slicing (and ::2
-slicing an empty slice would double the step, similarly to what builtins.range does: range(0, 0, 3)[::2] == range(0, 0, 6)
).
From a quick look, I'd guess that a proper fix would involve changing the internal representation of RangeCoordinateTransform from having start, stop, and size (well, dim_size) as attributes and step as a derived property to having start, size, and step as attributes and stop as a derived property.
Environment
xarray: 2025.7.1
pandas: 2.3.1
numpy: 2.3.1
scipy: 1.16.0
netCDF4: None
pydap: None
h5netcdf: None
h5py: 3.13.0
zarr: None
cftime: None
nc_time_axis: None
iris: None
bottleneck: None
dask: 2024.10.0
distributed: None
matplotlib: 3.11.0.dev1093+gb766c96c36
cartopy: None
seaborn: 0.13.2
numbagg: None
fsspec: 2024.9.0
cupy: None
pint: 0.24.4
sparse: None
flox: None
numpy_groupies: None
setuptools: 69.2.0
pip: 24.3.1
conda: None
pytest: 8.3.5
mypy: 1.15.0
IPython: 9.4.0
sphinx: 8.2.3