Skip to content

ENH: Implement arrow support for read_csv with engine=c #51128

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 7 commits into from
Feb 8, 2023
Merged
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
4 changes: 2 additions & 2 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,8 @@ The option will only work for functions with the keyword ``use_nullable_dtypes``
Additionally a new global configuration, ``mode.dtype_backend`` can now be used in conjunction with the parameter ``use_nullable_dtypes=True`` in the following functions
to select the nullable dtypes implementation.

* :func:`read_csv` (with ``engine="pyarrow"`` or ``engine="python"``)
* :func:`read_clipboard` (with ``engine="python"``)
* :func:`read_csv`
* :func:`read_clipboard`
* :func:`read_fwf`
* :func:`read_excel`
* :func:`read_html`
Expand Down
21 changes: 18 additions & 3 deletions pandas/_libs/parsers.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ from pandas.util._exceptions import find_stack_level

from pandas import StringDtype
from pandas.core.arrays import (
ArrowExtensionArray,
BooleanArray,
FloatingArray,
IntegerArray,
Expand Down Expand Up @@ -341,6 +342,7 @@ cdef class TextReader:
bint use_nullable_dtypes
object usecols
set unnamed_cols # set[str]
str dtype_backend

def __cinit__(self, source,
delimiter=b",", # bytes | str
Expand Down Expand Up @@ -377,7 +379,8 @@ cdef class TextReader:
float_precision=None,
bint skip_blank_lines=True,
encoding_errors=b"strict",
use_nullable_dtypes=False):
use_nullable_dtypes=False,
dtype_backend="pandas"):

# set encoding for native Python and C library
if isinstance(encoding_errors, str):
Expand Down Expand Up @@ -499,6 +502,7 @@ cdef class TextReader:
# - dict[Any, DtypeObj]
self.dtype = dtype
self.use_nullable_dtypes = use_nullable_dtypes
self.dtype_backend = dtype_backend

self.noconvert = set()

Expand Down Expand Up @@ -1054,7 +1058,9 @@ cdef class TextReader:
):
use_nullable_dtypes = self.use_nullable_dtypes and col_dtype is None
col_res = _maybe_upcast(
col_res, use_nullable_dtypes=use_nullable_dtypes
col_res,
use_nullable_dtypes=use_nullable_dtypes,
dtype_backend=self.dtype_backend,
)

if col_res is None:
Expand Down Expand Up @@ -1387,7 +1393,9 @@ STR_NA_VALUES = {
_NA_VALUES = _ensure_encoded(list(STR_NA_VALUES))


def _maybe_upcast(arr, use_nullable_dtypes: bool = False):
def _maybe_upcast(
arr, use_nullable_dtypes: bool = False, dtype_backend: str = "pandas"
):
"""Sets nullable dtypes or upcasts if nans are present.

Upcast, if use_nullable_dtypes is false and nans are present so that the
Expand Down Expand Up @@ -1440,6 +1448,13 @@ def _maybe_upcast(arr, use_nullable_dtypes: bool = False):
if use_nullable_dtypes:
arr = StringDtype().construct_array_type()._from_sequence(arr)

if use_nullable_dtypes and dtype_backend == "pyarrow":
import pyarrow as pa
if isinstance(arr, IntegerArray) and arr.isna().all():
# use null instead of int64 in pyarrow
arr = arr.to_numpy()
arr = ArrowExtensionArray(pa.array(arr, from_pandas=True))

return arr


Expand Down
2 changes: 0 additions & 2 deletions pandas/io/clipboards.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@ def read_clipboard(
numpy-backed nullable dtypes or
``pd.set_option("mode.dtype_backend", "pyarrow")`` to use
pyarrow-backed nullable dtypes (using ``pd.ArrowDtype``).
This is only implemented for the ``python``
engine.

.. versionadded:: 2.0

Expand Down
8 changes: 8 additions & 0 deletions pandas/io/parsers/c_parser_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@

import numpy as np

from pandas._config.config import get_option

from pandas._libs import parsers
from pandas._typing import (
ArrayLike,
DtypeArg,
DtypeObj,
ReadCsvBuffer,
)
from pandas.compat._optional import import_optional_dependency
from pandas.errors import DtypeWarning
from pandas.util._exceptions import find_stack_level

Expand Down Expand Up @@ -79,6 +82,11 @@ def __init__(self, src: ReadCsvBuffer[str], **kwds) -> None:
kwds.pop(key, None)

kwds["dtype"] = ensure_dtype_objs(kwds.get("dtype", None))
dtype_backend = get_option("mode.dtype_backend")
kwds["dtype_backend"] = dtype_backend
if dtype_backend == "pyarrow":
# Fail here loudly instead of in cython after reading
import_optional_dependency("pyarrow")
self._reader = parsers.TextReader(src, **kwds)

self.unnamed_cols = self._reader.unnamed_cols
Expand Down
16 changes: 1 addition & 15 deletions pandas/io/parsers/readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@

import numpy as np

from pandas._config import (
get_option,
using_nullable_dtypes,
)
from pandas._config import using_nullable_dtypes

from pandas._libs import lib
from pandas._libs.parsers import STR_NA_VALUES
Expand Down Expand Up @@ -408,8 +405,6 @@
numpy-backed nullable dtypes or
``pd.set_option("mode.dtype_backend", "pyarrow")`` to use
pyarrow-backed nullable dtypes (using ``pd.ArrowDtype``).
This is only implemented for the ``pyarrow`` or ``python``
engines.

.. versionadded:: 2.0

Expand Down Expand Up @@ -566,15 +561,6 @@ def _read(
raise ValueError(
"The 'chunksize' option is not supported with the 'pyarrow' engine"
)
elif (
kwds.get("use_nullable_dtypes", False)
and get_option("mode.dtype_backend") == "pyarrow"
and kwds.get("engine") == "c"
):
raise NotImplementedError(
f"use_nullable_dtypes=True and engine={kwds['engine']} with "
"mode.dtype_backend set to 'pyarrow' is not implemented."
)
else:
chunksize = validate_integer("chunksize", chunksize, 1)

Expand Down
9 changes: 1 addition & 8 deletions pandas/tests/io/parser/dtypes/test_dtypes_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,13 +500,6 @@ def test_use_nullable_dtypes_pyarrow_backend(all_parsers, request):
3,4.5,False,b,6,7.5,True,a,12-31-2019,
"""
with pd.option_context("mode.dtype_backend", "pyarrow"):
if engine == "c":
request.node.add_marker(
pytest.mark.xfail(
raises=NotImplementedError,
reason=f"Not implemented with engine={parser.engine}",
)
)
result = parser.read_csv(
StringIO(data), use_nullable_dtypes=True, parse_dates=["i"]
)
Expand All @@ -520,7 +513,7 @@ def test_use_nullable_dtypes_pyarrow_backend(all_parsers, request):
"f": pd.Series([pd.NA, 7.5], dtype="float64[pyarrow]"),
"g": pd.Series([pd.NA, True], dtype="bool[pyarrow]"),
"h": pd.Series(
[pd.NA if engine == "python" else "", "a"],
[pd.NA if engine != "pyarrow" else "", "a"],
dtype=pd.ArrowDtype(pa.string()),
),
"i": pd.Series([Timestamp("2019-12-31")] * 2),
Expand Down
3 changes: 0 additions & 3 deletions pandas/tests/io/test_clipboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,9 +426,6 @@ def test_read_clipboard_nullable_dtypes(
if string_storage == "pyarrow" or dtype_backend == "pyarrow":
pa = pytest.importorskip("pyarrow")

if dtype_backend == "pyarrow" and engine == "c":
pytest.skip(reason="c engine not yet supported")

if string_storage == "python":
string_array = StringArray(np.array(["x", "y"], dtype=np.object_))
string_array_na = StringArray(np.array(["x", NA], dtype=np.object_))
Expand Down