diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f0147859cae97..d5c3a95fa3b6a 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5447,7 +5447,7 @@ def astype( """ if is_dict_like(dtype): if self.ndim == 1: # i.e. Series - if len(dtype) > 1 or self.name not in dtype: + if len(dtype) > 1 or self.name not in dtype and errors == "raise": raise KeyError( "Only the Series name can be used for " "the key in Series dtype mappings." @@ -5456,7 +5456,7 @@ def astype( return self.astype(new_type, copy, errors) for col_name in dtype.keys(): - if col_name not in self: + if col_name not in self and errors == "raise": raise KeyError( "Only a column name can be used for the " "key in a dtype mappings argument." diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index 713d8f3ceeedb..4e048f02582fc 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -276,7 +276,7 @@ def test_astype_str_float(self): @pytest.mark.parametrize("dtype_class", [dict, Series]) def test_astype_dict_like(self, dtype_class): - # GH7271 & GH16717 + # GH7271 & GH16717 & GH30324 a = Series(date_range("2010-01-04", periods=5)) b = Series(range(5)) c = Series([0.0, 0.2, 0.4, 0.6, 0.8]) @@ -342,6 +342,15 @@ def test_astype_dict_like(self, dtype_class): tm.assert_frame_equal(df, equiv) tm.assert_frame_equal(df, original) + # GH 30324 + # If errors=='ignore' than the resulting DataFrame + # should be the same as the original DataFrame + dt8 = dtype_class({"b": str, 2: str}) + dt9 = dtype_class({"e": str}) + df.astype(dt8, errors="ignore") + df.astype(dt9, errors="ignore") + tm.assert_frame_equal(df, original) + def test_astype_duplicate_col(self): a1 = Series([1, 2, 3, 4, 5], name="a") b = Series([0.1, 0.2, 0.4, 0.6, 0.8], name="b")