From 87ef7cb9b55d4ce0ac1475ccd1915e8db0360a0c Mon Sep 17 00:00:00 2001 From: Tom Augspurger Date: Thu, 23 Jan 2020 09:26:38 -0600 Subject: [PATCH] Backport PR #31187: BUG: IntegerArray.astype(boolean) --- pandas/core/arrays/integer.py | 7 +++++++ pandas/tests/arrays/test_integer.py | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 67036761bc62a..022e6a7322872 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -19,6 +19,7 @@ is_list_like, is_object_dtype, is_scalar, + pandas_dtype, ) from pandas.core.dtypes.dtypes import register_extension_dtype from pandas.core.dtypes.missing import isna @@ -440,11 +441,17 @@ def astype(self, dtype, copy=True): if incompatible type with an IntegerDtype, equivalent of same_kind casting """ + from pandas.core.arrays.boolean import BooleanArray, BooleanDtype + + dtype = pandas_dtype(dtype) # if we are astyping to an existing IntegerDtype we can fastpath if isinstance(dtype, _IntegerDtype): result = self._data.astype(dtype.numpy_dtype, copy=False) return type(self)(result, mask=self._mask, copy=False) + elif isinstance(dtype, BooleanDtype): + result = self._data.astype("bool", copy=False) + return BooleanArray(result, mask=self._mask, copy=False) # coerce if is_float_dtype(dtype): diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py index f1a7cc741603d..3e9b880c01e91 100644 --- a/pandas/tests/arrays/test_integer.py +++ b/pandas/tests/arrays/test_integer.py @@ -680,6 +680,13 @@ def test_astype_str(self): tm.assert_numpy_array_equal(a.astype(str), expected) tm.assert_numpy_array_equal(a.astype("str"), expected) + def test_astype_boolean(self): + # https://github.com/pandas-dev/pandas/issues/31102 + a = pd.array([1, 0, -1, 2, None], dtype="Int64") + result = a.astype("boolean") + expected = pd.array([True, False, True, True, None], dtype="boolean") + tm.assert_extension_array_equal(result, expected) + def test_frame_repr(data_missing):