Skip to content

Commit 38acb4f

Browse files
committed
add tests and comments
1 parent 97b662d commit 38acb4f

File tree

4 files changed

+22
-2
lines changed

4 files changed

+22
-2
lines changed

doc/source/whatsnew/v0.22.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ Backwards incompatible API changes
4040
Other API Changes
4141
^^^^^^^^^^^^^^^^^
4242

43-
-
43+
- :func:`Series.truncate` and :func:`DataFrame.truncate` will raise a ``ValueError`` if the index is not sorted (:issue:`17935`)
4444
-
4545
-
4646

pandas/core/generic.py

+2
Original file line numberDiff line numberDiff line change
@@ -6356,6 +6356,8 @@ def truncate(self, before=None, after=None, axis=None, copy=True):
63566356
axis = self._get_axis_number(axis)
63576357
ax = self._get_axis(axis)
63586358

6359+
# GH 17935
6360+
# Check that index is sorted
63596361
if (not ax.is_monotonic_increasing and
63606362
not ax.is_monotonic_decreasing):
63616363
raise ValueError("truncate requires a sorted index")

pandas/tests/frame/test_timeseries.py

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

386386
rng = pd.date_range('2011-01-01', '2012-01-01', freq='W')
387-
ts = pd.Series(np.random.randn(len(rng)), index=rng)
387+
ts = pd.DataFrame({'A': np.random.randn(len(rng)),
388+
'B': np.random.randn(len(rng))},
389+
index=rng)
388390
with tm.assert_raises_regex(ValueError,
389391
'truncate requires a sorted index'):
390392
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)