Skip to content

Commit 6217901

Browse files
committed
ERR: Improve error message on non-sorted input with .truncate
1 parent c2590b3 commit 6217901

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
@@ -6338,6 +6338,10 @@ def truncate(self, before=None, after=None, axis=None, copy=True):
63386338
axis = self._get_axis_number(axis)
63396339
ax = self._get_axis(axis)
63406340

6341+
if (not ax.is_monotonic_increasing and
6342+
not ax.is_monotonic_decreasing):
6343+
raise ValueError("truncate requires a sorted index")
6344+
63416345
# if we have a date index, convert to dates, otherwise
63426346
# treat like a slice
63436347
if ax.is_all_dates:

pandas/tests/frame/test_timeseries.py

+25
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,31 @@ def test_truncate_copy(self):
377377
truncated.values[:] = 5.
378378
assert not (self.tsframe.values[5:11] == 5).any()
379379

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

0 commit comments

Comments
 (0)