Skip to content

BUG: read_csv with mixed bools and int sometimes reads 1 as a bool function. #43179

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions pandas/_libs/parsers.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1090,7 +1090,20 @@ cdef class TextReader:

# we had a fallback parse on the dtype, so now try to cast
# only allow safe casts, eg. with a nan you cannot safely cast to int
#floating casts are handled in this section
if col_res is not None and col_dtype is not None:
if is_float_dtype(col_dtype) and col_res.dtype == np.bool_ :
mask = col_res.view(np.uint8) == na_values[np.uint8]
col_res = col_res.astype(col_dtype)
np.putmask(col_res, mask, np.nan)
return col_res, na_count
if is_integer_dtype(col_dtype) and col_res.dtype == np.bool_ :
if na_count > 0:
raise ValueError(
f"cannot safely convert passed user dtype of "
f"{col_dtype} for {np.bool_} dtyped data in "
f"column {i} as it is applicable only in the case of float values and not NA values")
pass
try:
col_res = col_res.astype(col_dtype, casting='safe')
except TypeError:
Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/io/parser/test_na_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -590,3 +590,22 @@ def test_nan_multi_index(all_parsers):
)

tm.assert_frame_equal(result, expected)

def test_bool_and_nan_to_int(all_parsers):
p = all_parsers
test_data_val = """0 NaN True False"""
with pytest.raises(ValueError, match = "convert"):
print(p.read_csv(StringIO(test_data_val), dtype = "int"))

def test_bool_and_nan_to_float(all_parsers):
p = all_parsers
test_data_val = """0 NaN True False"""
result = p.read_csv(StringIO(test_data_val), dtype = "float")
expected = DataFrame.from_dict({"0": [np.nan, 1.0, 0.0]})
tm.assert_frame_equal(result, expected)

def test_bool_and_nan_to_bool(all_parsers):
p = all_parsers
test_data_val = """0 NaN True False """
with pytest.raises(ValueError, match = "NA values"):
p.read_csv(StringIO(test_data_val), dtype = "bool")