Repository: pandas-dev/pandas
Pull request: Fixed #34859: Added support for '0' and '1' in BooleanArray._from_sequence_of_strings method
- [ ] closes #34859 
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry


Problem statement:
BUG: ValueError: 1.0 and 0.0 cannot be cast to bool when using pd.read_csv()
- [x] I have checked that this issue has not already been reported.

- [x] I have confirmed this bug exists on the latest version of pandas.

- [ ] (optional) I have confirmed this bug exists on the master branch of pandas.

---

#### Code Sample

```python
import io
import pandas as pd

example_csv = """
boolean_column, string_column
1.0, a
0.0, b
,c"""

csv = io.StringIO(example_csv)
df = pd.read_csv(csv, dtype={"boolean_column": "boolean"})
```
```python-traceback
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-c698a4bcbc2d> in <module>
      1 csv = io.StringIO(example_csv)
----> 2 df = pd.read_csv(csv, dtype={"boolean_column": "boolean"})

c:\users\abbooda\appdata\local\continuum\miniconda3\envs\divi\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision)
    674         )
    675 
--> 676         return _read(filepath_or_buffer, kwds)
    677 
    678     parser_f.__name__ = name

c:\users\abbooda\appdata\local\continuum\miniconda3\envs\divi\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds)
    452 
    453     try:
--> 454         data = parser.read(nrows)
    455     finally:
    456         parser.close()

c:\users\abbooda\appdata\local\continuum\miniconda3\envs\divi\lib\site-packages\pandas\io\parsers.py in read(self, nrows)
   1131     def read(self, nrows=None):
   1132         nrows = _validate_integer("nrows", nrows)
-> 1133         ret = self._engine.read(nrows)
   1134 
   1135         # May alter columns / col_dict

c:\users\abbooda\appdata\local\continuum\miniconda3\envs\divi\lib\site-packages\pandas\io\parsers.py in read(self, nrows)
   2035     def read(self, nrows=None):
   2036         try:
-> 2037             data = self._reader.read(nrows)
   2038         except StopIteration:
   2039             if self._first_chunk:

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader.read()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._read_low_memory()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._read_rows()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._convert_column_data()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._convert_tokens()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._convert_with_dtype()

c:\users\abbooda\appdata\local\continuum\miniconda3\envs\divi\lib\site-packages\pandas\core\arrays\boolean.py in _from_sequence_of_strings(cls, strings, dtype, copy)
    302                 raise ValueError(f"{s} cannot be cast to bool")
    303 
--> 304         scalars = [map_string(x) for x in strings]
    305         return cls._from_sequence(scalars, dtype, copy)
    306 

c:\users\abbooda\appdata\local\continuum\miniconda3\envs\divi\lib\site-packages\pandas\core\arrays\boolean.py in <listcomp>(.0)
    302                 raise ValueError(f"{s} cannot be cast to bool")
    303 
--> 304         scalars = [map_string(x) for x in strings]
    305         return cls._from_sequence(scalars, dtype, copy)
    306 

c:\users\abbooda\appdata\local\continuum\miniconda3\envs\divi\lib\site-packages\pandas\core\arrays\boolean.py in map_string(s)
    300                 return False
    301             else:
--> 302                 raise ValueError(f"{s} cannot be cast to bool")
    303 
    304         scalars = [map_string(x) for x in strings]

ValueError: 1.0 cannot be cast to bool
```

#### Problem description

I would expect that 1.0, 0.0 and None can be cast to a nullable boolean. Using ``pd.read_csv()``  without dtype assignment assigns float64 dtype. Why does "boolean" not work?

#### Expected Output

```python
print(df)
>>>   boolean_column  string_column
0            True              a
1           False              b
2            <NA>              c
```

#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit           : None
python           : 3.7.6.final.0
python-bits      : 64
OS               : Windows
OS-release       : 10
machine          : AMD64
processor        : Intel64 Family 6 Model 158 Stepping 10, GenuineIntel
byteorder        : little
LC_ALL           : None
LANG             : en_US.UTF-8
LOCALE           : None.None

pandas           : 1.0.4
numpy            : 1.18.1
pytz             : 2020.1
dateutil         : 2.8.1
pip              : 20.1.1
setuptools       : 47.3.0.post20200616
Cython           : None
pytest           : None
hypothesis       : None
sphinx           : None
blosc            : None
feather          : None
xlsxwriter       : None
lxml.etree       : None
html5lib         : None
pymysql          : None
psycopg2         : None
jinja2           : 2.11.2
IPython          : 7.15.0
pandas_datareader: None
bs4              : None
bottleneck       : None
fastparquet      : None
gcsfs            : None
lxml.etree       : None
matplotlib       : 3.2.1
numexpr          : None
odfpy            : None
openpyxl         : 3.0.3
pandas_gbq       : None
pyarrow          : None
pytables         : None
pytest           : None
pyxlsb           : None
s3fs             : None
scipy            : None
sqlalchemy       : None
tables           : None
tabulate         : None
xarray           : None
xlrd             : None
xlwt             : None
xlsxwriter       : None
numba            : None

</details>

Hints from issue discussion:
I think this just hasn't been implemented yet. Converting floats came up when BooleanArray was added, but IIRC we kept things simple at first.

To fix, we'll want to update `BooleanArray._from_sequence_of_string`.

cc @jorisvandenbossche. 
Is this intended/desired to accept ``1``/``1.0``, ``0``/``0.0`` asbooleans? If so, I could update ``BooleanArray._from_sequence_of_string``.
Hey @TomAugspurger  and @jorisvandenbossche , do you think I should create a PR to enhance the ``BooleanArray._from_sequence_of_string`` function? I think it is worth it since it is not that uncommon to encode Booleans with 0 and 1 in a CSV and thus it would be nice to allow setting the nullable boolean for this column when reading the CSV.
This was discussed a bit in the original issue / PR implementing boolean array. You might want to read through it to get some context.

But IIRC the decision to not accept them at first was just for simplifying the initial implementation. I think we'd be find accepting them now.
Yes, I think at least 0's and 1's should be fine to accept (other numbers might require some extra discussion)

Commit message: Added support for '0' and '1' in BooleanArray._from_sequence_of_strings method

Patch to review:
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 040253ebe7279..a8d5763ae5abc 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -328,6 +328,7 @@ Other enhancements
 - :meth:`DataFrame.to_html` and :meth:`DataFrame.to_string`'s ``col_space`` parameter now accepts a list or dict to change only some specific columns' width (:issue:`28917`).
 - :meth:`DataFrame.to_excel` can now also write OpenOffice spreadsheet (.ods) files (:issue:`27222`)
 - :meth:`~Series.explode` now accepts ``ignore_index`` to reset the index, similarly to :meth:`pd.concat` or :meth:`DataFrame.sort_values` (:issue:`34932`).
+- :meth:`BooleanArray._from_sequence_of_strings` now accepts "0", "0.0", "1", "1.0" (:issue:`34859`)
 
 .. ---------------------------------------------------------------------------
 
diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py
index 9f1c2c6e668ad..dbce71b77a425 100644
--- a/pandas/core/arrays/boolean.py
+++ b/pandas/core/arrays/boolean.py
@@ -286,9 +286,9 @@ def _from_sequence_of_strings(
         def map_string(s):
             if isna(s):
                 return s
-            elif s in ["True", "TRUE", "true"]:
+            elif s in ["True", "TRUE", "true", "1", "1.0"]:
                 return True
-            elif s in ["False", "FALSE", "false"]:
+            elif s in ["False", "FALSE", "false", "0", "0.0"]:
                 return False
             else:
                 raise ValueError(f"{s} cannot be cast to bool")
diff --git a/pandas/tests/arrays/boolean/test_construction.py b/pandas/tests/arrays/boolean/test_construction.py
index f7354a089df3b..be19211947d63 100644
--- a/pandas/tests/arrays/boolean/test_construction.py
+++ b/pandas/tests/arrays/boolean/test_construction.py
@@ -247,10 +247,11 @@ def test_coerce_to_numpy_array():
 
 def test_to_boolean_array_from_strings():
     result = BooleanArray._from_sequence_of_strings(
-        np.array(["True", "False", np.nan], dtype=object)
+        np.array(["True", "False", "1.0", "0", np.nan], dtype=object)
     )
     expected = BooleanArray(
-        np.array([True, False, False]), np.array([False, False, True])
+        np.array([True, False, True, False, False]),
+        np.array([False, False, False, False, True]),
     )
 
     tm.assert_extension_array_equal(result, expected)


Code review comments:
diff_hunk: @@ -247,10 +247,11 @@ def test_coerce_to_numpy_array():
 
 def test_to_boolean_array_from_strings():
     result = BooleanArray._from_sequence_of_strings(
-        np.array(["True", "False", np.nan], dtype=object)
+        np.array(["True", "False", "1.0", "0", np.nan], dtype=object)
path: pandas/tests/arrays/boolean/test_construction.py
text: @user1:
Also "0.0" and "1"