diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 83df09d6b2cf3..e19021762792f 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -354,7 +354,7 @@ def _get_axis_number(cls, axis): return cls._AXIS_NUMBERS[axis] except KeyError: pass - raise ValueError(f"No axis named {axis} for object type {cls}") + raise ValueError(f"No axis named {axis} for object type {cls.__name__}") @classmethod def _get_axis_name(cls, axis): diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 3153a9ac28c10..954f99cda4211 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -685,7 +685,8 @@ def to_series(right): elif right.ndim > 2: raise ValueError( - f"Unable to coerce to Series/DataFrame, dim must be <= 2: {right.shape}" + "Unable to coerce to Series/DataFrame, " + f"dimension must be <= 2: {right.shape}" ) elif is_list_like(right) and not isinstance(right, (ABCSeries, ABCDataFrame)): diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index 9c52e8ec5620f..0eec30cbc5c67 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -100,13 +100,10 @@ def test_quantile_axis_parameter(self): result = df.quantile(0.5, axis="columns") tm.assert_series_equal(result, expected) - msg = "No axis named -1 for object type " + msg = "No axis named -1 for object type DataFrame" with pytest.raises(ValueError, match=msg): df.quantile(0.1, axis=-1) - msg = ( - "No axis named column for object type " - "" - ) + msg = "No axis named column for object type DataFrame" with pytest.raises(ValueError, match=msg): df.quantile(0.1, axis="column") diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index 5a25d1c2c0894..3d3bb98f80ac5 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -43,7 +43,7 @@ def test_sort_values(self): sorted_df = frame.sort_values(by=["B", "A"], ascending=[True, False]) tm.assert_frame_equal(sorted_df, expected) - msg = "No axis named 2 for object type " + msg = "No axis named 2 for object type DataFrame" with pytest.raises(ValueError, match=msg): frame.sort_values(by=["A", "B"], axis=2, inplace=True) diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 3964e790c7c12..3a7df29ae9091 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -919,7 +919,7 @@ def test_idxmin(self, float_frame, int_frame): expected = df.apply(Series.idxmin, axis=axis, skipna=skipna) tm.assert_series_equal(result, expected) - msg = "No axis named 2 for object type " + msg = "No axis named 2 for object type DataFrame" with pytest.raises(ValueError, match=msg): frame.idxmin(axis=2) @@ -934,7 +934,7 @@ def test_idxmax(self, float_frame, int_frame): expected = df.apply(Series.idxmax, axis=axis, skipna=skipna) tm.assert_series_equal(result, expected) - msg = "No axis named 2 for object type " + msg = "No axis named 2 for object type DataFrame" with pytest.raises(ValueError, match=msg): frame.idxmax(axis=2) diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 940a76601b75e..91627b46c2fee 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -371,10 +371,7 @@ def test_swapaxes(self): tm.assert_frame_equal(df.T, df.swapaxes(0, 1)) tm.assert_frame_equal(df.T, df.swapaxes(1, 0)) tm.assert_frame_equal(df, df.swapaxes(0, 0)) - msg = ( - "No axis named 2 for object type " - r"" - ) + msg = "No axis named 2 for object type DataFrame" with pytest.raises(ValueError, match=msg): df.swapaxes(2, 5) diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index ee3cd59c27b44..6dee4424f1cec 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -49,7 +49,8 @@ def test_apply(self, float_frame): # invalid axis df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], index=["a", "a", "c"]) - with pytest.raises(ValueError): + msg = "No axis named 2 for object type DataFrame" + with pytest.raises(ValueError, match=msg): df.apply(lambda x: x, 2) # GH 9573 @@ -221,7 +222,8 @@ def test_apply_broadcast_error(self, int_frame_const_col): df = int_frame_const_col # > 1 ndim - with pytest.raises(ValueError): + msg = "too many dims to broadcast" + with pytest.raises(ValueError, match=msg): df.apply( lambda x: np.array([1, 2]).reshape(-1, 2), axis=1, @@ -229,10 +231,11 @@ def test_apply_broadcast_error(self, int_frame_const_col): ) # cannot broadcast - with pytest.raises(ValueError): + msg = "cannot broadcast result" + with pytest.raises(ValueError, match=msg): df.apply(lambda x: [1, 2], axis=1, result_type="broadcast") - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): df.apply(lambda x: Series([1, 2]), axis=1, result_type="broadcast") def test_apply_raw(self, float_frame, mixed_type_frame): @@ -950,7 +953,11 @@ def test_result_type_error(self, result_type, int_frame_const_col): # allowed result_type df = int_frame_const_col - with pytest.raises(ValueError): + msg = ( + "invalid value for result_type, must be one of " + "{None, 'reduce', 'broadcast', 'expand'}" + ) + with pytest.raises(ValueError, match=msg): df.apply(lambda x: [1, 2, 3], axis=1, result_type=result_type) @pytest.mark.parametrize( @@ -1046,14 +1053,16 @@ def test_agg_transform(self, axis, float_frame): def test_transform_and_agg_err(self, axis, float_frame): # cannot both transform and agg - with pytest.raises(ValueError): + msg = "transforms cannot produce aggregated results" + with pytest.raises(ValueError, match=msg): float_frame.transform(["max", "min"], axis=axis) - with pytest.raises(ValueError): + msg = "cannot combine transform and aggregation operations" + with pytest.raises(ValueError, match=msg): with np.errstate(all="ignore"): float_frame.agg(["max", "sqrt"], axis=axis) - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): with np.errstate(all="ignore"): float_frame.transform(["max", "sqrt"], axis=axis) @@ -1387,7 +1396,8 @@ def test_agg_cython_table_transform(self, df, func, expected, axis): ) def test_agg_cython_table_raises(self, df, func, expected, axis): # GH 21224 - with pytest.raises(expected): + msg = "can't multiply sequence by non-int of type 'str'" + with pytest.raises(expected, match=msg): df.agg(func, axis=axis) @pytest.mark.parametrize("num_cols", [2, 3, 5]) diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index b39c58b9931ab..2150e1da9e8ad 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -1,6 +1,7 @@ from collections import deque from datetime import datetime import operator +import re import numpy as np import pytest @@ -46,13 +47,16 @@ def check(df, df2): ) tm.assert_frame_equal(result, expected) - with pytest.raises(TypeError): + msg = re.escape( + "Invalid comparison between dtype=datetime64[ns] and ndarray" + ) + with pytest.raises(TypeError, match=msg): x >= y - with pytest.raises(TypeError): + with pytest.raises(TypeError, match=msg): x > y - with pytest.raises(TypeError): + with pytest.raises(TypeError, match=msg): x < y - with pytest.raises(TypeError): + with pytest.raises(TypeError, match=msg): x <= y # GH4968 @@ -98,9 +102,13 @@ def test_timestamp_compare(self): result = right_f(pd.Timestamp("20010109"), df) tm.assert_frame_equal(result, expected) else: - with pytest.raises(TypeError): + msg = ( + "'(<|>)=?' not supported between " + "instances of 'Timestamp' and 'float'" + ) + with pytest.raises(TypeError, match=msg): left_f(df, pd.Timestamp("20010109")) - with pytest.raises(TypeError): + with pytest.raises(TypeError, match=msg): right_f(pd.Timestamp("20010109"), df) # nats expected = left_f(df, pd.Timestamp("nat")) diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 7effa98fd8213..ea21359c2f75c 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -173,13 +173,15 @@ def test_drop_api_equivalence(self): res2 = df.drop(index=["a"], columns=["d"]) tm.assert_frame_equal(res1, res2) - with pytest.raises(ValueError): + msg = "Cannot specify both 'labels' and 'index'/'columns'" + with pytest.raises(ValueError, match=msg): df.drop(labels="a", index="b") - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): df.drop(labels="a", columns="b") - with pytest.raises(ValueError): + msg = "Need to specify at least one of 'labels', 'index' or 'columns'" + with pytest.raises(ValueError, match=msg): df.drop(axis=1) def test_merge_join_different_levels(self): @@ -616,7 +618,8 @@ def test_align_float(self, float_frame): tm.assert_index_equal(bf.index, Index([])) # Try to align DataFrame to Series along bad axis - with pytest.raises(ValueError): + msg = "No axis named 2 for object type DataFrame" + with pytest.raises(ValueError, match=msg): float_frame.align(af.iloc[0, :3], join="inner", axis=2) # align dataframe to series with broadcast or not diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 95f812a99c579..9f40e8c6931c8 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2,6 +2,7 @@ from datetime import date, datetime, timedelta import functools import itertools +import re import numpy as np import numpy.ma as ma @@ -1401,7 +1402,8 @@ def test_constructor_list_of_dataclasses_error_thrown(self): Point = make_dataclass("Point", [("x", int), ("y", int)]) # expect TypeError - with pytest.raises(TypeError): + msg = "asdict() should be called on dataclass instances" + with pytest.raises(TypeError, match=re.escape(msg)): DataFrame([Point(0, 0), {"x": 1, "y": 0}]) def test_constructor_list_of_dict_order(self): diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index d1a7917bd127b..323a13a940ac3 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -1,5 +1,6 @@ from collections import OrderedDict from datetime import timedelta +import re import numpy as np import pytest @@ -636,7 +637,11 @@ def test_arg_for_errors_in_astype(self): df = DataFrame([1, 2, 3]) - with pytest.raises(ValueError): + msg = ( + "Expected value of kwarg 'errors' to be one of " + "['raise', 'ignore']. Supplied value is 'True'" + ) + with pytest.raises(ValueError, match=re.escape(msg)): df.astype(np.float64, errors=True) df.astype(np.int8, errors="ignore") diff --git a/pandas/tests/frame/test_missing.py b/pandas/tests/frame/test_missing.py index 196df8ba00476..470da25a922a1 100644 --- a/pandas/tests/frame/test_missing.py +++ b/pandas/tests/frame/test_missing.py @@ -114,7 +114,7 @@ def test_dropna(self): tm.assert_frame_equal(dropped, expected) # bad input - msg = "No axis named 3 for object type " + msg = "No axis named 3 for object type DataFrame" with pytest.raises(ValueError, match=msg): df.dropna(axis=3) diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index 542d9835bb5d3..4e37954726b93 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -1,5 +1,6 @@ from decimal import Decimal import operator +import re import numpy as np import pytest @@ -51,9 +52,13 @@ def test_neg_object(self, df, expected): ], ) def test_neg_raises(self, df): - with pytest.raises(TypeError): + msg = ( + "bad operand type for unary -: 'str'|" + r"Unary negative expects numeric dtype, not datetime64\[ns\]" + ) + with pytest.raises(TypeError, match=msg): (-df) - with pytest.raises(TypeError): + with pytest.raises(TypeError, match=msg): (-df["a"]) def test_invert(self, float_frame): @@ -116,9 +121,10 @@ def test_pos_object(self, df): "df", [pd.DataFrame({"a": pd.to_datetime(["2017-01-22", "1970-01-01"])})] ) def test_pos_raises(self, df): - with pytest.raises(TypeError): + msg = re.escape("Unary plus expects numeric dtype, not datetime64[ns]") + with pytest.raises(TypeError, match=msg): (+df) - with pytest.raises(TypeError): + with pytest.raises(TypeError, match=msg): (+df["a"]) @@ -173,12 +179,14 @@ def test_logical_ops_invalid(self): df1 = DataFrame(1.0, index=[1], columns=["A"]) df2 = DataFrame(True, index=[1], columns=["A"]) - with pytest.raises(TypeError): + msg = re.escape("unsupported operand type(s) for |: 'float' and 'bool'") + with pytest.raises(TypeError, match=msg): df1 | df2 df1 = DataFrame("foo", index=[1], columns=["A"]) df2 = DataFrame(True, index=[1], columns=["A"]) - with pytest.raises(TypeError): + msg = re.escape("unsupported operand type(s) for |: 'str' and 'bool'") + with pytest.raises(TypeError, match=msg): df1 | df2 def test_logical_operators(self): @@ -565,7 +573,11 @@ def test_comp(func): result = func(df1, df2) tm.assert_numpy_array_equal(result.values, func(df1.values, df2.values)) - with pytest.raises(ValueError, match="dim must be <= 2"): + msg = ( + "Unable to coerce to Series/DataFrame, " + "dimension must be <= 2: (30, 4, 1, 1, 1)" + ) + with pytest.raises(ValueError, match=re.escape(msg)): func(df1, ndim_5) result2 = func(simple_frame, row) @@ -594,7 +606,8 @@ def test_strings_to_numbers_comparisons_raises(self, compare_operators_no_eq_ne) ) f = getattr(operator, compare_operators_no_eq_ne) - with pytest.raises(TypeError): + msg = "'[<>]=?' not supported between instances of 'str' and 'int'" + with pytest.raises(TypeError, match=msg): f(df, 0) def test_comparison_protected_from_errstate(self): @@ -881,9 +894,12 @@ def test_alignment_non_pandas(self): align(df, val, "columns") val = np.zeros((3, 3, 3)) - with pytest.raises(ValueError): + msg = re.escape( + "Unable to coerce to Series/DataFrame, dimension must be <= 2: (3, 3, 3)" + ) + with pytest.raises(ValueError, match=msg): align(df, val, "index") - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): align(df, val, "columns") def test_no_warning(self, all_arithmetic_operators): diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index 46a4a0a2af4ba..4f039baa5c7bd 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -695,10 +695,11 @@ def test_unstack_dtypes(self): def test_unstack_non_unique_index_names(self): idx = MultiIndex.from_tuples([("a", "b"), ("c", "d")], names=["c1", "c1"]) df = DataFrame([1, 2], index=idx) - with pytest.raises(ValueError): + msg = "The name c1 occurs multiple times, use a level number" + with pytest.raises(ValueError, match=msg): df.unstack("c1") - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=msg): df.T.stack("c1") def test_unstack_unused_levels(self): diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index 6999dea6adfa3..f6005a0f839a3 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -692,10 +692,10 @@ def test_squeeze(self): tm.assert_series_equal(df.squeeze(axis=1), df.iloc[:, 0]) tm.assert_series_equal(df.squeeze(axis="columns"), df.iloc[:, 0]) assert df.squeeze() == df.iloc[0, 0] - msg = "No axis named 2 for object type " + msg = "No axis named 2 for object type DataFrame" with pytest.raises(ValueError, match=msg): df.squeeze(axis=2) - msg = "No axis named x for object type " + msg = "No axis named x for object type DataFrame" with pytest.raises(ValueError, match=msg): df.squeeze(axis="x") diff --git a/pandas/tests/series/methods/test_between_time.py b/pandas/tests/series/methods/test_between_time.py index 3fa26afe77a1d..e9d2f8e6f1637 100644 --- a/pandas/tests/series/methods/test_between_time.py +++ b/pandas/tests/series/methods/test_between_time.py @@ -139,6 +139,6 @@ def test_between_time_axis(self): assert len(ts.between_time(stime, etime)) == expected_length assert len(ts.between_time(stime, etime, axis=0)) == expected_length - msg = "No axis named 1 for object type " + msg = "No axis named 1 for object type Series" with pytest.raises(ValueError, match=msg): ts.between_time(stime, etime, axis=1) diff --git a/pandas/tests/series/methods/test_rank.py b/pandas/tests/series/methods/test_rank.py index 3d4688c8274f9..caaffb7d5b61f 100644 --- a/pandas/tests/series/methods/test_rank.py +++ b/pandas/tests/series/methods/test_rank.py @@ -202,9 +202,7 @@ def test_rank_categorical(self): def test_rank_signature(self): s = Series([0, 1]) s.rank(method="average") - msg = ( - "No axis named average for object type " - ) + msg = "No axis named average for object type Series" with pytest.raises(ValueError, match=msg): s.rank("average") diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py index 6fa4eeaee34c0..d4ebc9062a0c9 100644 --- a/pandas/tests/series/methods/test_sort_index.py +++ b/pandas/tests/series/methods/test_sort_index.py @@ -30,7 +30,7 @@ def test_sort_index(self, datetime_series): sorted_series = random_order.sort_index(axis=0) tm.assert_series_equal(sorted_series, datetime_series) - msg = "No axis named 1 for object type " + msg = "No axis named 1 for object type Series" with pytest.raises(ValueError, match=msg): random_order.sort_values(axis=1) diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index bac005465034f..15f1bc8941d47 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -823,7 +823,7 @@ def test_dropna_empty(self): assert len(s) == 0 # invalid axis - msg = "No axis named 1 for object type " + msg = "No axis named 1 for object type Series" with pytest.raises(ValueError, match=msg): s.dropna(axis=1)