Skip to content

Commit 69c9324

Browse files
committed
ERR: Improve error message on non-sorted input with .truncate
1 parent 058da72 commit 69c9324

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

pandas/core/generic.py

+4
Original file line numberDiff line numberDiff line change
@@ -6397,6 +6397,10 @@ def truncate(self, before=None, after=None, axis=None, copy=True):
63976397
axis = self._get_axis_number(axis)
63986398
ax = self._get_axis(axis)
63996399

6400+
if (not ax.is_monotonic_increasing and
6401+
not ax.is_monotonic_decreasing):
6402+
raise ValueError("truncate requires a sorted index")
6403+
64006404
# if we have a date index, convert to dates, otherwise
64016405
# treat like a slice
64026406
if ax.is_all_dates:

pandas/tests/frame/test_timeseries.py

+25
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,31 @@ def test_truncate_copy(self):
374374
truncated.values[:] = 5.
375375
assert not (self.tsframe.values[5:11] == 5).any()
376376

377+
def test_truncate_nonsortedindex(self):
378+
# GH 17935
379+
380+
df = pd.DataFrame({'A': ['a', 'b', 'c', 'd', 'e']},
381+
index=[5, 3, 2, 9, 0])
382+
with tm.assert_raises_regex(ValueError,
383+
'truncate requires a sorted index'):
384+
df.truncate(before=3, after=9)
385+
386+
rng = pd.date_range('2011-01-01', '2012-01-01', freq='W')
387+
ts = pd.Series(np.random.randn(len(rng)), index=rng)
388+
with tm.assert_raises_regex(ValueError,
389+
'truncate requires a sorted index'):
390+
ts.sort_values(ascending=False).truncate(before='2011-11',
391+
after='2011-12')
392+
393+
df = pd.DataFrame({3: np.random.randn(5),
394+
20: np.random.randn(5),
395+
2: np.random.randn(5),
396+
0: np.random.randn(5)},
397+
columns=[3, 20, 2, 0])
398+
with tm.assert_raises_regex(ValueError,
399+
'truncate requires a sorted index'):
400+
df.truncate(before=2, after=20, axis=1)
401+
377402
def test_asfreq(self):
378403
offset_monthly = self.tsframe.asfreq(offsets.BMonthEnd())
379404
rule_monthly = self.tsframe.asfreq('BM')

0 commit comments

Comments
 (0)