Skip to content

Commit 798e855

Browse files
jbrockmendeltm9k1
authored andcommitted
validate min/max axis (pandas-dev#23206)
* validate min/max axis closes pandas-dev#23081 * Fix copy/paste indentation mistake * Fix merge mixup
1 parent 6b01665 commit 798e855

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

pandas/compat/numpy/function.py

+21
Original file line numberDiff line numberDiff line change
@@ -360,3 +360,24 @@ def validate_resampler_func(method, args, kwargs):
360360
"{func}() instead".format(func=method)))
361361
else:
362362
raise TypeError("too many arguments passed in")
363+
364+
365+
def validate_minmax_axis(axis):
366+
"""
367+
Ensure that the axis argument passed to min, max, argmin, or argmax is
368+
zero or None, as otherwise it will be incorrectly ignored.
369+
370+
Parameters
371+
----------
372+
axis : int or None
373+
374+
Raises
375+
------
376+
ValueError
377+
"""
378+
ndim = 1 # hard-coded for Index
379+
if axis is None:
380+
return
381+
if axis >= ndim or (axis < 0 and ndim + axis < 0):
382+
raise ValueError("`axis` must be fewer than the number of "
383+
"dimensions ({ndim})".format(ndim=ndim))

pandas/core/indexes/datetimelike.py

+4
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,7 @@ def min(self, axis=None, *args, **kwargs):
431431
numpy.ndarray.min
432432
"""
433433
nv.validate_min(args, kwargs)
434+
nv.validate_minmax_axis(axis)
434435

435436
try:
436437
i8 = self.asi8
@@ -459,6 +460,7 @@ def argmin(self, axis=None, *args, **kwargs):
459460
numpy.ndarray.argmin
460461
"""
461462
nv.validate_argmin(args, kwargs)
463+
nv.validate_minmax_axis(axis)
462464

463465
i8 = self.asi8
464466
if self.hasnans:
@@ -479,6 +481,7 @@ def max(self, axis=None, *args, **kwargs):
479481
numpy.ndarray.max
480482
"""
481483
nv.validate_max(args, kwargs)
484+
nv.validate_minmax_axis(axis)
482485

483486
try:
484487
i8 = self.asi8
@@ -507,6 +510,7 @@ def argmax(self, axis=None, *args, **kwargs):
507510
numpy.ndarray.argmax
508511
"""
509512
nv.validate_argmax(args, kwargs)
513+
nv.validate_minmax_axis(axis)
510514

511515
i8 = self.asi8
512516
if self.hasnans:

pandas/tests/indexes/datetimelike.py

+12
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,18 @@
88

99
class DatetimeLike(Base):
1010

11+
def test_argmax_axis_invalid(self):
12+
# GH#23081
13+
rng = self.create_index()
14+
with pytest.raises(ValueError):
15+
rng.argmax(axis=1)
16+
with pytest.raises(ValueError):
17+
rng.argmin(axis=2)
18+
with pytest.raises(ValueError):
19+
rng.min(axis=-2)
20+
with pytest.raises(ValueError):
21+
rng.max(axis=-3)
22+
1123
def test_can_hold_identifiers(self):
1224
idx = self.create_index()
1325
key = idx[0]

0 commit comments

Comments
 (0)