Skip to content

Commit f4232e7

Browse files
natmokvalmroeschke
andauthored
CLN: remove unnecessary check needs_i8_conversion if Index subclass does not support any or all (#58006)
* cln-remove-unnecessary-check-needs_i8_conversion * fix tests * remove the check self.dtype.kind, fix tests * Update pandas/core/indexes/base.py Co-authored-by: Matthew Roeschke <[email protected]> * combine two branches in test_logical_compat * correct test_logical_compat * correct test_logical_compat * correct test_logical_compat * roll back the check for datetime64 in test_logical_compat * replace reduction with operation to unify err msg * delete unused line --------- Co-authored-by: Matthew Roeschke <[email protected]>
1 parent ec3eddd commit f4232e7

19 files changed

+66
-78
lines changed

pandas/core/arrays/arrow/array.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1697,7 +1697,7 @@ def pyarrow_meth(data, skip_nulls, **kwargs):
16971697
except (AttributeError, NotImplementedError, TypeError) as err:
16981698
msg = (
16991699
f"'{type(self).__name__}' with dtype {self.dtype} "
1700-
f"does not support reduction '{name}' with pyarrow "
1700+
f"does not support operation '{name}' with pyarrow "
17011701
f"version {pa.__version__}. '{name}' may be supported by "
17021702
f"upgrading pyarrow."
17031703
)

pandas/core/arrays/base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1886,7 +1886,7 @@ def _reduce(
18861886
18871887
Raises
18881888
------
1889-
TypeError : subclass does not define reductions
1889+
TypeError : subclass does not define operations
18901890
18911891
Examples
18921892
--------
@@ -1897,7 +1897,7 @@ def _reduce(
18971897
if meth is None:
18981898
raise TypeError(
18991899
f"'{type(self).__name__}' with dtype {self.dtype} "
1900-
f"does not support reduction '{name}'"
1900+
f"does not support operation '{name}'"
19011901
)
19021902
result = meth(skipna=skipna, **kwargs)
19031903
if keepdims:

pandas/core/arrays/datetimelike.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1662,7 +1662,7 @@ def _groupby_op(
16621662
if dtype.kind == "M":
16631663
# Adding/multiplying datetimes is not valid
16641664
if how in ["any", "all", "sum", "prod", "cumsum", "cumprod", "var", "skew"]:
1665-
raise TypeError(f"datetime64 type does not support operation: '{how}'")
1665+
raise TypeError(f"datetime64 type does not support operation '{how}'")
16661666

16671667
elif isinstance(dtype, PeriodDtype):
16681668
# Adding/multiplying Periods is not valid

pandas/core/indexes/base.py

+2-9
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,6 @@
176176
)
177177
from pandas.core.missing import clean_reindex_fill_method
178178
from pandas.core.ops import get_op_result_name
179-
from pandas.core.ops.invalid import make_invalid_op
180179
from pandas.core.sorting import (
181180
ensure_key_mapped,
182181
get_group_index_sorter,
@@ -6942,14 +6941,8 @@ def _maybe_disable_logical_methods(self, opname: str_t) -> None:
69426941
"""
69436942
raise if this Index subclass does not support any or all.
69446943
"""
6945-
if (
6946-
isinstance(self, ABCMultiIndex)
6947-
# TODO(3.0): PeriodArray and DatetimeArray any/all will raise,
6948-
# so checking needs_i8_conversion will be unnecessary
6949-
or (needs_i8_conversion(self.dtype) and self.dtype.kind != "m")
6950-
):
6951-
# This call will raise
6952-
make_invalid_op(opname)(self)
6944+
if isinstance(self, ABCMultiIndex):
6945+
raise TypeError(f"cannot perform {opname} with {type(self).__name__}")
69536946

69546947
@Appender(IndexOpsMixin.argmin.__doc__)
69556948
def argmin(self, axis=None, skipna: bool = True, *args, **kwargs) -> int:

pandas/core/nanops.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,7 @@ def nanany(
520520

521521
if values.dtype.kind == "M":
522522
# GH#34479
523-
raise TypeError("datetime64 type does not support operation: 'any'")
523+
raise TypeError("datetime64 type does not support operation 'any'")
524524

525525
values, _ = _get_values(values, skipna, fill_value=False, mask=mask)
526526

@@ -576,7 +576,7 @@ def nanall(
576576

577577
if values.dtype.kind == "M":
578578
# GH#34479
579-
raise TypeError("datetime64 type does not support operation: 'all'")
579+
raise TypeError("datetime64 type does not support operation 'all'")
580580

581581
values, _ = _get_values(values, skipna, fill_value=True, mask=mask)
582582

pandas/tests/apply/test_frame_apply.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1209,7 +1209,7 @@ def test_agg_multiple_mixed_raises():
12091209
)
12101210

12111211
# sorted index
1212-
msg = "does not support reduction"
1212+
msg = "does not support operation"
12131213
with pytest.raises(TypeError, match=msg):
12141214
mdf.agg(["min", "sum"])
12151215

@@ -1309,15 +1309,15 @@ def test_nuiscance_columns():
13091309
)
13101310
tm.assert_frame_equal(result, expected)
13111311

1312-
msg = "does not support reduction"
1312+
msg = "does not support operation"
13131313
with pytest.raises(TypeError, match=msg):
13141314
df.agg("sum")
13151315

13161316
result = df[["A", "B", "C"]].agg("sum")
13171317
expected = Series([6, 6.0, "foobarbaz"], index=["A", "B", "C"])
13181318
tm.assert_series_equal(result, expected)
13191319

1320-
msg = "does not support reduction"
1320+
msg = "does not support operation"
13211321
with pytest.raises(TypeError, match=msg):
13221322
df.agg(["sum"])
13231323

pandas/tests/arrays/categorical/test_operators.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -374,14 +374,14 @@ def test_numeric_like_ops(self):
374374
# min/max)
375375
s = df["value_group"]
376376
for op in ["kurt", "skew", "var", "std", "mean", "sum", "median"]:
377-
msg = f"does not support reduction '{op}'"
377+
msg = f"does not support operation '{op}'"
378378
with pytest.raises(TypeError, match=msg):
379379
getattr(s, op)(numeric_only=False)
380380

381381
def test_numeric_like_ops_series(self):
382382
# numpy ops
383383
s = Series(Categorical([1, 2, 3, 4]))
384-
with pytest.raises(TypeError, match="does not support reduction 'sum'"):
384+
with pytest.raises(TypeError, match="does not support operation 'sum'"):
385385
np.sum(s)
386386

387387
@pytest.mark.parametrize(

pandas/tests/arrays/test_datetimelike.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ def test_scalar_from_string(self, arr1d):
247247
assert result == arr1d[0]
248248

249249
def test_reduce_invalid(self, arr1d):
250-
msg = "does not support reduction 'not a method'"
250+
msg = "does not support operation 'not a method'"
251251
with pytest.raises(TypeError, match=msg):
252252
arr1d._reduce("not a method")
253253

pandas/tests/extension/base/groupby.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ def test_in_numeric_groupby(self, data_for_grouping):
165165
# period
166166
"does not support sum operations",
167167
# datetime
168-
"does not support operation: 'sum'",
168+
"does not support operation 'sum'",
169169
# all others
170170
re.escape(f"agg function failed [how->sum,dtype->{dtype}"),
171171
]

pandas/tests/extension/base/reduce.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def test_reduce_series_boolean(self, data, all_boolean_reductions, skipna):
8686
# TODO: the message being checked here isn't actually checking anything
8787
msg = (
8888
"[Cc]annot perform|Categorical is not ordered for operation|"
89-
"does not support reduction|"
89+
"does not support operation|"
9090
)
9191

9292
with pytest.raises(TypeError, match=msg):
@@ -105,7 +105,7 @@ def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna):
105105
# TODO: the message being checked here isn't actually checking anything
106106
msg = (
107107
"[Cc]annot perform|Categorical is not ordered for operation|"
108-
"does not support reduction|"
108+
"does not support operation|"
109109
)
110110

111111
with pytest.raises(TypeError, match=msg):

pandas/tests/extension/test_datetime.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ def _supports_reduction(self, obj, op_name: str) -> bool:
104104
@pytest.mark.parametrize("skipna", [True, False])
105105
def test_reduce_series_boolean(self, data, all_boolean_reductions, skipna):
106106
meth = all_boolean_reductions
107-
msg = f"datetime64 type does not support operation: '{meth}'"
107+
msg = f"datetime64 type does not support operation '{meth}'"
108108
with pytest.raises(TypeError, match=msg):
109109
super().test_reduce_series_boolean(data, all_boolean_reductions, skipna)
110110

pandas/tests/frame/test_reductions.py

+16-16
Original file line numberDiff line numberDiff line change
@@ -975,7 +975,7 @@ def test_sum_mixed_datetime(self):
975975
df = DataFrame({"A": date_range("2000", periods=4), "B": [1, 2, 3, 4]}).reindex(
976976
[2, 3, 4]
977977
)
978-
with pytest.raises(TypeError, match="does not support reduction 'sum'"):
978+
with pytest.raises(TypeError, match="does not support operation 'sum'"):
979979
df.sum()
980980

981981
def test_mean_corner(self, float_frame, float_string_frame):
@@ -1381,7 +1381,7 @@ def test_any_datetime(self):
13811381
]
13821382
df = DataFrame({"A": float_data, "B": datetime_data})
13831383

1384-
msg = "datetime64 type does not support operation: 'any'"
1384+
msg = "datetime64 type does not support operation 'any'"
13851385
with pytest.raises(TypeError, match=msg):
13861386
df.any(axis=1)
13871387

@@ -1466,18 +1466,18 @@ def test_any_all_np_func(self, func, data, expected):
14661466

14671467
if any(isinstance(x, CategoricalDtype) for x in data.dtypes):
14681468
with pytest.raises(
1469-
TypeError, match="dtype category does not support reduction"
1469+
TypeError, match=".* dtype category does not support operation"
14701470
):
14711471
func(data)
14721472

14731473
# method version
14741474
with pytest.raises(
1475-
TypeError, match="dtype category does not support reduction"
1475+
TypeError, match=".* dtype category does not support operation"
14761476
):
14771477
getattr(DataFrame(data), func.__name__)(axis=None)
14781478
if data.dtypes.apply(lambda x: x.kind == "M").any():
14791479
# GH#34479
1480-
msg = "datetime64 type does not support operation: '(any|all)'"
1480+
msg = "datetime64 type does not support operation '(any|all)'"
14811481
with pytest.raises(TypeError, match=msg):
14821482
func(data)
14831483

@@ -1734,19 +1734,19 @@ def test_any_all_categorical_dtype_nuisance_column(self, all_boolean_reductions)
17341734
df = ser.to_frame()
17351735

17361736
# Double-check the Series behavior is to raise
1737-
with pytest.raises(TypeError, match="does not support reduction"):
1737+
with pytest.raises(TypeError, match="does not support operation"):
17381738
getattr(ser, all_boolean_reductions)()
17391739

1740-
with pytest.raises(TypeError, match="does not support reduction"):
1740+
with pytest.raises(TypeError, match="does not support operation"):
17411741
getattr(np, all_boolean_reductions)(ser)
17421742

1743-
with pytest.raises(TypeError, match="does not support reduction"):
1743+
with pytest.raises(TypeError, match="does not support operation"):
17441744
getattr(df, all_boolean_reductions)(bool_only=False)
17451745

1746-
with pytest.raises(TypeError, match="does not support reduction"):
1746+
with pytest.raises(TypeError, match="does not support operation"):
17471747
getattr(df, all_boolean_reductions)(bool_only=None)
17481748

1749-
with pytest.raises(TypeError, match="does not support reduction"):
1749+
with pytest.raises(TypeError, match="does not support operation"):
17501750
getattr(np, all_boolean_reductions)(df, axis=0)
17511751

17521752
def test_median_categorical_dtype_nuisance_column(self):
@@ -1755,22 +1755,22 @@ def test_median_categorical_dtype_nuisance_column(self):
17551755
ser = df["A"]
17561756

17571757
# Double-check the Series behavior is to raise
1758-
with pytest.raises(TypeError, match="does not support reduction"):
1758+
with pytest.raises(TypeError, match="does not support operation"):
17591759
ser.median()
17601760

1761-
with pytest.raises(TypeError, match="does not support reduction"):
1761+
with pytest.raises(TypeError, match="does not support operation"):
17621762
df.median(numeric_only=False)
17631763

1764-
with pytest.raises(TypeError, match="does not support reduction"):
1764+
with pytest.raises(TypeError, match="does not support operation"):
17651765
df.median()
17661766

17671767
# same thing, but with an additional non-categorical column
17681768
df["B"] = df["A"].astype(int)
17691769

1770-
with pytest.raises(TypeError, match="does not support reduction"):
1770+
with pytest.raises(TypeError, match="does not support operation"):
17711771
df.median(numeric_only=False)
17721772

1773-
with pytest.raises(TypeError, match="does not support reduction"):
1773+
with pytest.raises(TypeError, match="does not support operation"):
17741774
df.median()
17751775

17761776
# TODO: np.median(df, axis=0) gives np.array([2.0, 2.0]) instead
@@ -1964,7 +1964,7 @@ def test_minmax_extensionarray(method, numeric_only):
19641964
def test_frame_mixed_numeric_object_with_timestamp(ts_value):
19651965
# GH 13912
19661966
df = DataFrame({"a": [1], "b": [1.1], "c": ["foo"], "d": [ts_value]})
1967-
with pytest.raises(TypeError, match="does not support reduction"):
1967+
with pytest.raises(TypeError, match="does not support operation"):
19681968
df.sum()
19691969

19701970

pandas/tests/groupby/test_groupby.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -671,7 +671,7 @@ def test_raises_on_nuisance(df):
671671
df = df.loc[:, ["A", "C", "D"]]
672672
df["E"] = datetime.now()
673673
grouped = df.groupby("A")
674-
msg = "datetime64 type does not support operation: 'sum'"
674+
msg = "datetime64 type does not support operation 'sum'"
675675
with pytest.raises(TypeError, match=msg):
676676
grouped.agg("sum")
677677
with pytest.raises(TypeError, match=msg):
@@ -1794,7 +1794,7 @@ def get_categorical_invalid_expected():
17941794
else:
17951795
msg = "category type does not support"
17961796
if op == "skew":
1797-
msg = "|".join([msg, "does not support reduction 'skew'"])
1797+
msg = "|".join([msg, "does not support operation 'skew'"])
17981798
with pytest.raises(TypeError, match=msg):
17991799
get_result()
18001800

0 commit comments

Comments
 (0)