Skip to content

Commit a679553

Browse files
committed
add tests and comments
1 parent 6217901 commit a679553

File tree

4 files changed

+24
-1
lines changed

4 files changed

+24
-1
lines changed

doc/source/whatsnew/v0.22.0.txt

+3
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ Other API Changes
4646
- :class:`Timestamp` will no longer silently ignore invalid ``freq`` arguments (:issue:`5168`)
4747
- :class:`CacheableOffset` and :class:`WeekDay` are no longer available in the ``pandas.tseries.offsets`` module (:issue:`17830`)
4848
- `tseries.frequencies.get_freq_group()` and `tseries.frequencies.DAYS` are removed from the public API (:issue:`18034`)
49+
=======
50+
- :func:`Series.truncate` and :func:`DataFrame.truncate` will raise a ``ValueError`` if the index is not sorted (:issue:`17935`)
51+
4952

5053
.. _whatsnew_0220.deprecations:
5154

pandas/core/generic.py

+2
Original file line numberDiff line numberDiff line change
@@ -6338,6 +6338,8 @@ 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+
# GH 17935
6342+
# Check that index is sorted
63416343
if (not ax.is_monotonic_increasing and
63426344
not ax.is_monotonic_decreasing):
63436345
raise ValueError("truncate requires a sorted index")

pandas/tests/frame/test_timeseries.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,9 @@ def test_truncate_nonsortedindex(self):
387387
df.truncate(before=3, after=9)
388388

389389
rng = pd.date_range('2011-01-01', '2012-01-01', freq='W')
390-
ts = pd.Series(np.random.randn(len(rng)), index=rng)
390+
ts = pd.DataFrame({'A': np.random.randn(len(rng)),
391+
'B': np.random.randn(len(rng))},
392+
index=rng)
391393
with tm.assert_raises_regex(ValueError,
392394
'truncate requires a sorted index'):
393395
ts.sort_values(ascending=False).truncate(before='2011-11',

pandas/tests/series/test_timeseries.py

+16
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,22 @@ def test_truncate(self):
236236
before=self.ts.index[-1] + offset,
237237
after=self.ts.index[0] - offset)
238238

239+
def test_truncate_nonsortedindex(self):
240+
# GH 17935
241+
242+
s = pd.Series(['a', 'b', 'c', 'd', 'e'],
243+
index=[5, 3, 2, 9, 0])
244+
with tm.assert_raises_regex(ValueError,
245+
'truncate requires a sorted index'):
246+
s.truncate(before=3, after=9)
247+
248+
rng = pd.date_range('2011-01-01', '2012-01-01', freq='W')
249+
ts = pd.Series(np.random.randn(len(rng)), index=rng)
250+
with tm.assert_raises_regex(ValueError,
251+
'truncate requires a sorted index'):
252+
ts.sort_values(ascending=False).truncate(before='2011-11',
253+
after='2011-12')
254+
239255
def test_asfreq(self):
240256
ts = Series([0., 1., 2.], index=[datetime(2009, 10, 30), datetime(
241257
2009, 11, 30), datetime(2009, 12, 31)])

0 commit comments

Comments
 (0)