Pandas version checks
-
[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.
-
[ ] I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
from pathlib import Path
import pandas as pd
# Save this into a Excel sheet, adjust path if needed
# 1 True c
# a b True
# True 1 1
filex = Path(__file__).parent / "intbool.xlsx"
# Read with Excel, getting:
# 0 1 2
# 0 1 True c
# 1 a b True
# 2 1 True True
dfx = pd.read_excel(filex, header=None, dtype=str)
print(dfx)
Issue Description
Weird interaction between Python & Excel. When both integers and booleans of the same value are present on the same column (1/True or 0/False), read_excel
will cast all these to the value that appears first in each series.
- Behaviour tested with Openpyxl & Calamine.
- I expected that setting
dtype=str
would fix the issue, but it had no effect read_csv
doesn't have this issue. The data would be read as strings- writing Excel file from dataframe of strings will format excel content as string, thus preventing the issue to happen
I tracked the issue down to sanitize_objects
coded in Cython. I believe the issue is from this piece of code:
* Iterations over the content of the column. memo
stores the values already known.
* When current value val
is in memo
, reuse it.
* As 1 == True
is true, the first value of 1/True found in the series is used for all the upcoming 1/True. Similar behaviour with 0/False
https://github.com/pandas-dev/pandas/blob/e87248e1a5d6d78a138039f2856a3aec6b9fef54/pandas/_libs/parsers.pyx#L2143-L2144
Expected Behavior
I may not have the full picture, but i guess
* current behaviour is fine when there are no strings in the series
* when strings are found in the series, read everything as strings ? Not sure of this one
* setting dtype=str
in read_excel
should read the series as containing only str
s, thus preventing this conversion
Installed Versions
Comment From: asishm
Thanks for the report. This seems to be a duplicate of https://github.com/pandas-dev/pandas/issues/60088