Skip to content

Commit c08d426

Browse files
committed
fix zero length RangeIndex + add tests
1 parent ce8b8a4 commit c08d426

File tree

4 files changed

+16
-2
lines changed

4 files changed

+16
-2
lines changed

pandas/core/indexes/range.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,8 @@ def _format_data(self, name=None):
188188
return None
189189

190190
def _format_with_header(self, header: List[str], na_rep: str = "NaN") -> List[str]:
191+
if len(self._range) == 0:
192+
return []
191193
first_val_str = str(self._range[0])
192194
last_val_str = str(self._range[-1])
193195
max_length = max(len(first_val_str), len(last_val_str))

pandas/tests/indexes/common.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import gc
2-
from typing import Optional, Type
2+
from typing import Type
33

44
import numpy as np
55
import pytest
@@ -33,7 +33,7 @@
3333
class Base:
3434
""" base class for index sub-class tests """
3535

36-
_holder: Optional[Type[Index]] = None
36+
_holder: Type[Index]
3737
_compat_props = ["shape", "ndim", "size", "nbytes"]
3838

3939
def create_index(self) -> Index:
@@ -681,6 +681,10 @@ def test_format(self):
681681
expected = [str(x) for x in idx]
682682
assert idx.format() == expected
683683

684+
def test_format_empty(self):
685+
# GH35712
686+
assert self._holder([]).format() == []
687+
684688
def test_hasnans_isnans(self, index):
685689
# GH 11343, added tests for hasnans / isnans
686690
if isinstance(index, MultiIndex):

pandas/tests/indexes/period/test_period.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,6 +536,10 @@ def test_contains_raise_error_if_period_index_is_in_multi_index(self, msg, key):
536536
with pytest.raises(KeyError, match=msg):
537537
df.loc[key]
538538

539+
def test_format_empty(self):
540+
# GH35712
541+
assert self._holder([], freq="A").format() == []
542+
539543

540544
def test_maybe_convert_timedelta():
541545
pi = PeriodIndex(["2000", "2001"], freq="D")

pandas/tests/indexes/ranges/test_range.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -521,3 +521,7 @@ def test_engineless_lookup(self):
521521
idx.get_loc("a")
522522

523523
assert "_engine" not in idx._cache
524+
525+
def test_format_empty(self):
526+
# GH35712
527+
assert self._holder(0).format() == []

0 commit comments

Comments
 (0)