Skip to content

ENH: Implement _from_sequence_of_strings for BooleanArray #31159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 23 commits into from
Jan 23, 2020
Merged
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ type dedicated to boolean data that can hold missing values. The default
``bool`` data type based on a bool-dtype NumPy array, the column can only hold
``True`` or ``False``, and not missing values. This new :class:`~arrays.BooleanArray`
can store missing values as well by keeping track of this in a separate mask.
(:issue:`29555`, :issue:`30095`)
(:issue:`29555`, :issue:`30095`, :issue:`31131`)

.. ipython:: python

Expand Down
19 changes: 18 additions & 1 deletion pandas/core/arrays/boolean.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import numbers
from typing import TYPE_CHECKING, Any, Tuple, Type
from typing import TYPE_CHECKING, Any, List, Tuple, Type
import warnings

import numpy as np
Expand Down Expand Up @@ -286,6 +286,23 @@ def _from_sequence(cls, scalars, dtype=None, copy: bool = False):
values, mask = coerce_to_array(scalars, copy=copy)
return BooleanArray(values, mask)

@classmethod
def _from_sequence_of_strings(
cls, strings: List[str], dtype=None, copy: bool = False
):
def map_string(s):
if isna(s):
return s
elif s in ["True", "TRUE", "true"]:
return True
elif s in ["False", "FALSE", "false"]:
return False
else:
raise ValueError(f"{s} cannot be cast to bool")

scalars = [map_string(x) for x in strings]
return cls._from_sequence(scalars, dtype, copy)

def _values_for_factorize(self) -> Tuple[np.ndarray, Any]:
data = self._data.astype("int8")
data[self._mask] = -1
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/arrays/test_boolean.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,20 @@ def test_coerce_to_numpy_array():
np.array(arr, dtype="bool")


def test_to_boolean_array_from_strings():
result = BooleanArray._from_sequence_of_strings(
np.array(["True", "False", np.nan], dtype=object)
)
expected = BooleanArray(np.array([True, False]), np.array([False, False]))

tm.assert_extension_array_equal(result, expected)


def test_to_boolean_array_from_strings_invalid_string():
with pytest.raises(ValueError, match="cannot be cast"):
BooleanArray._from_sequence_of_strings(["donkey"])


def test_repr():
df = pd.DataFrame({"A": pd.array([True, False, None], dtype="boolean")})
expected = " A\n0 True\n1 False\n2 <NA>"
Expand Down
32 changes: 32 additions & 0 deletions pandas/tests/io/parser/test_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,3 +550,35 @@ def test_numeric_dtype(all_parsers, dtype):

result = parser.read_csv(StringIO(data), header=None, dtype=dtype)
tm.assert_frame_equal(expected, result)


def test_boolean_dtype(all_parsers):
parser = all_parsers
data = "\n".join(
[
"a",
"True",
"TRUE",
"true",
"False",
"FALSE",
"false",
"NaN",
"nan",
"NA",
"null",
"NULL",
]
)

result = parser.read_csv(StringIO(data), dtype="boolean")
expected = pd.DataFrame(
{
"a": pd.array(
[True, True, True, False, False, False, None, None, None, None, None],
dtype="boolean",
)
}
)

tm.assert_frame_equal(result, expected)