Skip to content

Commit 8d64fe9

Browse files
authored
BUG: truncate has incorrect behavior when index has only one unique v… (#42366)
1 parent 35b338e commit 8d64fe9

File tree

4 files changed

+20
-2
lines changed

4 files changed

+20
-2
lines changed

doc/source/whatsnew/v1.4.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ Interval
213213
Indexing
214214
^^^^^^^^
215215
- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`DatetimeIndex` when passing a string, the return type depended on whether the index was monotonic (:issue:`24892`)
216-
-
216+
- Bug in :meth:`DataFrame.truncate` and :meth:`Series.truncate` when the object's Index has a length greater than one but only one unique value (:issue:`42365`)
217217

218218
Missing
219219
^^^^^^^

pandas/core/generic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -9382,7 +9382,7 @@ def truncate(
93829382
if before is not None and after is not None and before > after:
93839383
raise ValueError(f"Truncate: {after} must be after {before}")
93849384

9385-
if len(ax) > 1 and ax.is_monotonic_decreasing:
9385+
if len(ax) > 1 and ax.is_monotonic_decreasing and ax.nunique() > 1:
93869386
before, after = after, before
93879387

93889388
slicer = [slice(None, None)] * self._AXIS_LEN

pandas/tests/frame/methods/test_truncate.py

+10
Original file line numberDiff line numberDiff line change
@@ -148,3 +148,13 @@ def test_truncate_multiindex(self, frame_or_series):
148148
expected = expected["col"]
149149

150150
tm.assert_equal(result, expected)
151+
152+
def test_truncate_index_only_one_unique_value(self, frame_or_series):
153+
# GH 42365
154+
obj = Series(0, index=date_range("2021-06-30", "2021-06-30")).repeat(5)
155+
if frame_or_series is DataFrame:
156+
obj = obj.to_frame(name="a")
157+
158+
truncated = obj.truncate("2021-06-28", "2021-07-01")
159+
160+
tm.assert_equal(truncated, obj)

pandas/tests/series/methods/test_truncate.py

+8
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,11 @@ def test_truncate_one_element_series(self):
5555

5656
# the input Series and the expected Series are the same
5757
tm.assert_series_equal(result, series)
58+
59+
def test_truncate_index_only_one_unique_value(self):
60+
# GH 42365
61+
obj = Series(0, index=date_range("2021-06-30", "2021-06-30")).repeat(5)
62+
63+
truncated = obj.truncate("2021-06-28", "2021-07-01")
64+
65+
tm.assert_series_equal(truncated, obj)

0 commit comments

Comments
 (0)