Skip to content

Commit 0bb2fa1

Browse files
meeseeksmachineWillAyd
authored andcommitted
Backport PR pandas-dev#31187: BUG: IntegerArray.astype(boolean) (pandas-dev#31254)
1 parent 978ad36 commit 0bb2fa1

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

pandas/core/arrays/integer.py

+7
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
is_list_like,
2020
is_object_dtype,
2121
is_scalar,
22+
pandas_dtype,
2223
)
2324
from pandas.core.dtypes.dtypes import register_extension_dtype
2425
from pandas.core.dtypes.missing import isna
@@ -440,11 +441,17 @@ def astype(self, dtype, copy=True):
440441
if incompatible type with an IntegerDtype, equivalent of same_kind
441442
casting
442443
"""
444+
from pandas.core.arrays.boolean import BooleanArray, BooleanDtype
445+
446+
dtype = pandas_dtype(dtype)
443447

444448
# if we are astyping to an existing IntegerDtype we can fastpath
445449
if isinstance(dtype, _IntegerDtype):
446450
result = self._data.astype(dtype.numpy_dtype, copy=False)
447451
return type(self)(result, mask=self._mask, copy=False)
452+
elif isinstance(dtype, BooleanDtype):
453+
result = self._data.astype("bool", copy=False)
454+
return BooleanArray(result, mask=self._mask, copy=False)
448455

449456
# coerce
450457
if is_float_dtype(dtype):

pandas/tests/arrays/test_integer.py

+7
Original file line numberDiff line numberDiff line change
@@ -680,6 +680,13 @@ def test_astype_str(self):
680680
tm.assert_numpy_array_equal(a.astype(str), expected)
681681
tm.assert_numpy_array_equal(a.astype("str"), expected)
682682

683+
def test_astype_boolean(self):
684+
# https://github.com/pandas-dev/pandas/issues/31102
685+
a = pd.array([1, 0, -1, 2, None], dtype="Int64")
686+
result = a.astype("boolean")
687+
expected = pd.array([True, False, True, True, None], dtype="boolean")
688+
tm.assert_extension_array_equal(result, expected)
689+
683690

684691
def test_frame_repr(data_missing):
685692

0 commit comments

Comments
 (0)