|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from pandas._typing import FilePathOrBuffer |
| 4 | +from pandas.compat._optional import import_optional_dependency |
| 5 | + |
| 6 | +from pandas.core.dtypes.inference import is_integer |
| 7 | + |
| 8 | +from pandas.core.frame import DataFrame |
| 9 | + |
| 10 | +from pandas.io.common import get_handle |
| 11 | +from pandas.io.parsers.base_parser import ParserBase |
| 12 | + |
| 13 | + |
| 14 | +class ArrowParserWrapper(ParserBase): |
| 15 | + """ |
| 16 | + Wrapper for the pyarrow engine for read_csv() |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self, src: FilePathOrBuffer, **kwds): |
| 20 | + self.kwds = kwds |
| 21 | + self.src = src |
| 22 | + |
| 23 | + ParserBase.__init__(self, kwds) |
| 24 | + |
| 25 | + self._parse_kwds() |
| 26 | + |
| 27 | + def _parse_kwds(self): |
| 28 | + """ |
| 29 | + Validates keywords before passing to pyarrow. |
| 30 | + """ |
| 31 | + encoding: str | None = self.kwds.get("encoding") |
| 32 | + self.encoding = "utf-8" if encoding is None else encoding |
| 33 | + |
| 34 | + self.usecols, self.usecols_dtype = self._validate_usecols_arg( |
| 35 | + self.kwds["usecols"] |
| 36 | + ) |
| 37 | + na_values = self.kwds["na_values"] |
| 38 | + if isinstance(na_values, dict): |
| 39 | + raise ValueError( |
| 40 | + "The pyarrow engine doesn't support passing a dict for na_values" |
| 41 | + ) |
| 42 | + self.na_values = list(self.kwds["na_values"]) |
| 43 | + |
| 44 | + def _get_pyarrow_options(self): |
| 45 | + """ |
| 46 | + Rename some arguments to pass to pyarrow |
| 47 | + """ |
| 48 | + mapping = { |
| 49 | + "usecols": "include_columns", |
| 50 | + "na_values": "null_values", |
| 51 | + "escapechar": "escape_char", |
| 52 | + "skip_blank_lines": "ignore_empty_lines", |
| 53 | + } |
| 54 | + for pandas_name, pyarrow_name in mapping.items(): |
| 55 | + if pandas_name in self.kwds and self.kwds.get(pandas_name) is not None: |
| 56 | + self.kwds[pyarrow_name] = self.kwds.pop(pandas_name) |
| 57 | + |
| 58 | + self.parse_options = { |
| 59 | + option_name: option_value |
| 60 | + for option_name, option_value in self.kwds.items() |
| 61 | + if option_value is not None |
| 62 | + and option_name |
| 63 | + in ("delimiter", "quote_char", "escape_char", "ignore_empty_lines") |
| 64 | + } |
| 65 | + self.convert_options = { |
| 66 | + option_name: option_value |
| 67 | + for option_name, option_value in self.kwds.items() |
| 68 | + if option_value is not None |
| 69 | + and option_name |
| 70 | + in ("include_columns", "null_values", "true_values", "false_values") |
| 71 | + } |
| 72 | + self.read_options = { |
| 73 | + "autogenerate_column_names": self.header is None, |
| 74 | + "skip_rows": self.header |
| 75 | + if self.header is not None |
| 76 | + else self.kwds["skiprows"], |
| 77 | + } |
| 78 | + |
| 79 | + def _finalize_output(self, frame: DataFrame) -> DataFrame: |
| 80 | + """ |
| 81 | + Processes data read in based on kwargs. |
| 82 | +
|
| 83 | + Parameters |
| 84 | + ---------- |
| 85 | + frame: DataFrame |
| 86 | + The DataFrame to process. |
| 87 | +
|
| 88 | + Returns |
| 89 | + ------- |
| 90 | + DataFrame |
| 91 | + The processed DataFrame. |
| 92 | + """ |
| 93 | + num_cols = len(frame.columns) |
| 94 | + if self.header is None: |
| 95 | + if self.names is None: |
| 96 | + if self.prefix is not None: |
| 97 | + self.names = [f"{self.prefix}{i}" for i in range(num_cols)] |
| 98 | + elif self.header is None: |
| 99 | + self.names = range(num_cols) |
| 100 | + frame.columns = self.names |
| 101 | + # we only need the frame not the names |
| 102 | + frame.columns, frame = self._do_date_conversions(frame.columns, frame) |
| 103 | + if self.index_col is not None: |
| 104 | + for i, item in enumerate(self.index_col): |
| 105 | + if is_integer(item): |
| 106 | + self.index_col[i] = frame.columns[item] |
| 107 | + frame.set_index(self.index_col, drop=True, inplace=True) |
| 108 | + |
| 109 | + if self.kwds.get("dtype") is not None: |
| 110 | + frame = frame.astype(self.kwds.get("dtype")) |
| 111 | + return frame |
| 112 | + |
| 113 | + def read(self) -> DataFrame: |
| 114 | + """ |
| 115 | + Reads the contents of a CSV file into a DataFrame and |
| 116 | + processes it according to the kwargs passed in the |
| 117 | + constructor. |
| 118 | +
|
| 119 | + Returns |
| 120 | + ------- |
| 121 | + DataFrame |
| 122 | + The DataFrame created from the CSV file. |
| 123 | + """ |
| 124 | + pyarrow_csv = import_optional_dependency("pyarrow.csv") |
| 125 | + self._get_pyarrow_options() |
| 126 | + |
| 127 | + with get_handle( |
| 128 | + self.src, "rb", encoding=self.encoding, is_text=False |
| 129 | + ) as handles: |
| 130 | + table = pyarrow_csv.read_csv( |
| 131 | + handles.handle, |
| 132 | + read_options=pyarrow_csv.ReadOptions(**self.read_options), |
| 133 | + parse_options=pyarrow_csv.ParseOptions(**self.parse_options), |
| 134 | + convert_options=pyarrow_csv.ConvertOptions(**self.convert_options), |
| 135 | + ) |
| 136 | + |
| 137 | + frame = table.to_pandas() |
| 138 | + return self._finalize_output(frame) |
0 commit comments