Skip to content

BUG: truncate has incorrect behavior when index has only one unique v… #42366

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ Interval
Indexing
^^^^^^^^
- 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`)
-
- 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`)

Missing
^^^^^^^
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -9381,7 +9381,7 @@ def truncate(
if before is not None and after is not None and before > after:
raise ValueError(f"Truncate: {after} must be after {before}")

if len(ax) > 1 and ax.is_monotonic_decreasing:
if len(ax) > 1 and ax.is_monotonic_decreasing and ax.nunique() > 1:
before, after = after, before

slicer = [slice(None, None)] * self._AXIS_LEN
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/frame/methods/test_truncate.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,13 @@ def test_truncate_multiindex(self, frame_or_series):
expected = expected["col"]

tm.assert_equal(result, expected)

def test_truncate_index_only_one_unique_value(self, frame_or_series):
# GH 42365
obj = Series(0, index=date_range("2021-06-30", "2021-06-30")).repeat(5)
if frame_or_series is DataFrame:
obj = obj.to_frame(name="a")

truncated = obj.truncate("2021-06-28", "2021-07-01")

tm.assert_equal(truncated, obj)
8 changes: 8 additions & 0 deletions pandas/tests/series/methods/test_truncate.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,11 @@ def test_truncate_one_element_series(self):

# the input Series and the expected Series are the same
tm.assert_series_equal(result, series)

def test_truncate_index_only_one_unique_value(self):
# GH 42365
obj = Series(0, index=date_range("2021-06-30", "2021-06-30")).repeat(5)

truncated = obj.truncate("2021-06-28", "2021-07-01")

tm.assert_series_equal(truncated, obj)