diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index c58ee3818cbd9..1bf7fa00d07b2 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -812,6 +812,7 @@ Numeric Conversion ^^^^^^^^^^ - Bug in constructing :class:`Series` with ``int64`` dtype from a string list raising instead of casting (:issue:`44923`) +- Bug in constructing :class:`Series` with masked dtype and boolean values with ``NA`` raising (:issue:`42137`) - Bug in :meth:`DataFrame.eval` incorrectly raising an ``AttributeError`` when there are negative values in function call (:issue:`46471`) - Bug in :meth:`Series.convert_dtypes` not converting dtype to nullable dtype when :class:`Series` contains ``NA`` and has dtype ``object`` (:issue:`48791`) - Bug where any :class:`ExtensionDtype` subclass with ``kind="M"`` would be interpreted as a timezone type (:issue:`34986`) diff --git a/pandas/core/arrays/numeric.py b/pandas/core/arrays/numeric.py index 48d3bc5c495a8..0a30c28acb090 100644 --- a/pandas/core/arrays/numeric.py +++ b/pandas/core/arrays/numeric.py @@ -172,9 +172,7 @@ def _coerce_to_data_and_mask(values, mask, dtype, copy, dtype_cls, default_dtype inferred_type = None if is_object_dtype(values.dtype) or is_string_dtype(values.dtype): inferred_type = lib.infer_dtype(values, skipna=True) - if inferred_type == "empty": - pass - elif inferred_type == "boolean": + if inferred_type == "boolean" and dtype is None: name = dtype_cls.__name__.strip("_") raise TypeError(f"{values.dtype} cannot be converted to {name}") diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 0d320b6c4e5d4..a4e82838b61d3 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1987,6 +1987,21 @@ def test_constructor_mismatched_null_nullable_dtype( with pytest.raises(TypeError, match=msg): func([null, 1.0, 3.0], dtype=any_numeric_ea_dtype) + def test_series_constructor_ea_int_from_bool(self): + # GH#42137 + result = Series([True, False, True, pd.NA], dtype="Int64") + expected = Series([1, 0, 1, pd.NA], dtype="Int64") + tm.assert_series_equal(result, expected) + + result = Series([True, False, True], dtype="Int64") + expected = Series([1, 0, 1], dtype="Int64") + tm.assert_series_equal(result, expected) + + def test_series_constructor_ea_int_from_string_bool(self): + # GH#42137 + with pytest.raises(ValueError, match="invalid literal"): + Series(["True", "False", "True", pd.NA], dtype="Int64") + class TestSeriesConstructorIndexCoercion: def test_series_constructor_datetimelike_index_coercion(self):