diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 49b2349851479..a2bacbbc09b2c 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -275,7 +275,7 @@ Numeric Conversion ^^^^^^^^^^ -- +- Bug in :func:`DataFrame.astype()` when passing a dict of columns and types the `errors` parameter was ignored. (:issue:`25905`) - - diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 9797069566b4b..245f4403e3b5e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5716,7 +5716,8 @@ def astype(self, dtype, copy=True, errors='raise', **kwargs): results = [] for col_name, col in self.iteritems(): if col_name in dtype: - results.append(col.astype(dtype[col_name], copy=copy)) + results.append(col.astype(dtype=dtype[col_name], copy=copy, + errors=errors, **kwargs)) else: results.append(results.append(col.copy() if copy else col)) diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index 90a21961ef78d..11c6a524239a1 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -850,6 +850,20 @@ def test_arg_for_errors_in_astype(self): df.astype(np.int8, errors='ignore') + def test_arg_for_errors_in_astype_dictlist(self): + # GH-25905 + df = pd.DataFrame([ + {'a': '1', 'b': '16.5%', 'c': 'test'}, + {'a': '2.2', 'b': '15.3', 'c': 'another_test'}]) + expected = pd.DataFrame([ + {'a': 1.0, 'b': '16.5%', 'c': 'test'}, + {'a': 2.2, 'b': '15.3', 'c': 'another_test'}]) + type_dict = {'a': 'float64', 'b': 'float64', 'c': 'object'} + + result = df.astype(dtype=type_dict, errors='ignore') + + tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize('input_vals', [ ([1, 2]), (['1', '2']),