Open dadrake3 opened 8 months ago
can confirm this in 2.2.1
Do you get the same result when you use the pyarrow.csv.read_csv
method directly? https://arrow.apache.org/docs/python/generated/pyarrow.csv.read_csv.html
seems to be a problem with the pyarrow engine in pandas (pandas 2.2.1, pyarrow 15.0.1)
pandas engine pandas dtype: 01
pyarrow engine pandas dtype: 1
pandas engine pyarrow dtype: 01
pyarrow engine pyarrow dtype: 1
pyarrow native: 01
import io
import pandas as pd
import pyarrow as pa
from pyarrow import csv
csv_file = io.BytesIO(
"""a
01""".encode()
)
print(f"pandas engine pandas dtype: {pd.read_csv(csv_file, dtype=str).iloc[0,0]}")
csv_file.seek(0)
print(
f"pyarrow engine pandas dtype: {pd.read_csv(csv_file, dtype=str, engine='pyarrow').iloc[0,0]}"
)
csv_file.seek(0)
print(
f"pandas engine pyarrow dtype: {pd.read_csv(csv_file, dtype='str[pyarrow]').iloc[0,0]}"
)
csv_file.seek(0)
print(
f"pyarrow engine pyarrow dtype: {pd.read_csv(csv_file, dtype='str[pyarrow]', engine='pyarrow').iloc[0,0]}"
)
csv_file.seek(0)
convert_options = csv.ConvertOptions(column_types={"a": pa.string()})
print(
f"pyarrow native: {csv.read_csv(csv_file, convert_options=convert_options).column(0).to_pylist()[0]}"
)
take
For context, the reason this is happening is because currrently the dtype
argument is only handled as post-processing after pyarrow has read the CSV file. So, currently, we let pyarrow read the csv file with inferring (in this case) numerical types, and then afterwards we cast the result to the specified dtype (in this case str
). So that explains why the leading zeros are lost.
PyArrow does provide a column_types
keyword to specify the dtype while reading: https://arrow.apache.org/docs/python/generated/pyarrow.csv.ConvertOptions.html#pyarrow.csv.ConvertOptions
So what we need to do is translate the dtype
keyword in read_csv
to the column_types
argument for pyarrow, somewhere here:
As a first step, I would just try to enable specifying it for a specific column, like dtype={"a": str}
, because for something like dtype=str
which applies to all columns, with the current pyarrow API you would need to know the column names up front (pyarrow only accepts specifying it per column, not for all columns at once)
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.
[X] I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
Issue Description
when I use engine=pyarrow and set dtype to str i am seeing the leading zeros in my numeric columns removed even though the resulting column type is 'O'. When I use the python engine I see that the leading zeros are still there as expected.
Expected Behavior
I would expect when treating all columns as strings that the leading zeros are retained and the data is unmodified.
Installed Versions