Skip to content

Commit b6c47b0

Browse files
committed
add tests and comments
1 parent 14aa28c commit b6c47b0

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
@@ -45,6 +45,9 @@ Other API Changes
4545
- :class:`Timestamp` will no longer silently ignore unused or invalid ``tz`` or ``tzinfo`` keyword arguments (:issue:`17690`)
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`)
48+
- :func:`Series.truncate` and :func:`DataFrame.truncate` will raise a ``ValueError`` if the index is not sorted (:issue:`17935`)
49+
-
50+
-
4851

4952
.. _whatsnew_0220.deprecations:
5053

pandas/core/generic.py

+2
Original file line numberDiff line numberDiff line change
@@ -6337,6 +6337,8 @@ def truncate(self, before=None, after=None, axis=None, copy=True):
63376337
axis = self._get_axis_number(axis)
63386338
ax = self._get_axis(axis)
63396339

6340+
# GH 17935
6341+
# Check that index is sorted
63406342
if (not ax.is_monotonic_increasing and
63416343
not ax.is_monotonic_decreasing):
63426344
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)