@@ -166,6 +166,62 @@ def test_range_index_isel() -> None:
166166 assert_identical (actual , expected )
167167
168168
169+ def test_range_index_empty_slice () -> None :
170+ """Test that empty slices of RangeIndex are printable and preserve step.
171+
172+ Regression test for https://github.com/pydata/xarray/issues/10547
173+ """
174+ # Test with linspace
175+ n = 30
176+ step = 1
177+ da = xr .DataArray (np .zeros (n ), dims = ["x" ])
178+ da = da .assign_coords (
179+ xr .Coordinates .from_xindex (RangeIndex .linspace (0 , (n - 1 ) * step , n , dim = "x" ))
180+ )
181+
182+ # This should not raise ZeroDivisionError
183+ sub = da .isel (x = slice (0 ))
184+ assert sub .sizes ["x" ] == 0
185+
186+ # Test that it's printable
187+ repr_str = repr (sub )
188+ assert "RangeIndex" in repr_str
189+ assert "step=1" in repr_str
190+
191+ # Test with different step values
192+ index = RangeIndex .arange (0 , 10 , 2.5 , dim = "y" )
193+ da2 = xr .DataArray (np .zeros (4 ), dims = ["y" ])
194+ da2 = da2 .assign_coords (xr .Coordinates .from_xindex (index ))
195+ empty = da2 .isel (y = slice (0 ))
196+
197+ # Should preserve step
198+ assert empty .sizes ["y" ] == 0
199+ range_index_y = empty ._indexes ["y" ]
200+ assert isinstance (range_index_y , RangeIndex )
201+ assert range_index_y .step == 2.5
202+
203+ # Test that it's printable
204+ repr_str2 = repr (empty )
205+ assert "RangeIndex" in repr_str2
206+ assert "step=2.5" in repr_str2
207+
208+ # Test negative step
209+ index3 = RangeIndex .arange (10 , 0 , - 1 , dim = "z" )
210+ da3 = xr .DataArray (np .zeros (10 ), dims = ["z" ])
211+ da3 = da3 .assign_coords (xr .Coordinates .from_xindex (index3 ))
212+ empty3 = da3 .isel (z = slice (0 ))
213+
214+ assert empty3 .sizes ["z" ] == 0
215+ range_index_z = empty3 ._indexes ["z" ]
216+ assert isinstance (range_index_z , RangeIndex )
217+ assert range_index_z .step == - 1.0
218+
219+ # Test that it's printable
220+ repr_str3 = repr (empty3 )
221+ assert "RangeIndex" in repr_str3
222+ assert "step=-1" in repr_str3
223+
224+
169225def test_range_index_sel () -> None :
170226 ds = create_dataset_arange (0.0 , 1.0 , 0.1 )
171227
0 commit comments