From e4b32187dd2a843ef55ea28db0bab085e2c995af Mon Sep 17 00:00:00 2001 From: Tom Augspurger Date: Tue, 21 Jan 2020 15:59:08 -0600 Subject: [PATCH 1/2] BUG: IntegerArray.astype(boolean) Closes https://github.com/pandas-dev/pandas/issues/31102 --- 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 9cb1e4176df96..ec462e7a63a80 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, None], dtype="Int64") + result = a.astype("boolean") + expected = pd.array([True, False, None], dtype="boolean") + tm.assert_extension_array_equal(result, expected) + def test_frame_repr(data_missing): From 219aae9c92050d90737749be838e9002434fd27e Mon Sep 17 00:00:00 2001 From: Tom Augspurger Date: Thu, 23 Jan 2020 06:33:49 -0600 Subject: [PATCH 2/2] other values --- pandas/tests/arrays/test_integer.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py index ec462e7a63a80..96e676018a0d6 100644 --- a/pandas/tests/arrays/test_integer.py +++ b/pandas/tests/arrays/test_integer.py @@ -682,9 +682,9 @@ def test_astype_str(self): def test_astype_boolean(self): # https://github.com/pandas-dev/pandas/issues/31102 - a = pd.array([1, 0, None], dtype="Int64") + a = pd.array([1, 0, -1, 2, None], dtype="Int64") result = a.astype("boolean") - expected = pd.array([True, False, None], dtype="boolean") + expected = pd.array([True, False, True, True, None], dtype="boolean") tm.assert_extension_array_equal(result, expected)