-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
batched_reader.py
140 lines (124 loc) · 4.72 KB
/
batched_reader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
from __future__ import annotations
import contextlib
from typing import TYPE_CHECKING, Sequence
from polars._utils.various import (
_process_null_values,
normalize_filepath,
)
from polars._utils.wrap import wrap_df
from polars.datatypes import N_INFER_DEFAULT, py_type_to_dtype
from polars.io._utils import parse_columns_arg, parse_row_index_args
from polars.io.csv._utils import _update_columns
with contextlib.suppress(ImportError): # Module not available when building docs
from polars.polars import PyBatchedCsv
if TYPE_CHECKING:
from pathlib import Path
from polars import DataFrame
from polars.type_aliases import CsvEncoding, PolarsDataType, SchemaDict
class BatchedCsvReader:
"""Read a CSV file in batches."""
def __init__(
self,
source: str | Path,
*,
has_header: bool = True,
columns: Sequence[int] | Sequence[str] | None = None,
separator: str = ",",
comment_prefix: str | None = None,
quote_char: str | None = '"',
skip_rows: int = 0,
dtypes: None | (SchemaDict | Sequence[PolarsDataType]) = None,
null_values: str | Sequence[str] | dict[str, str] | None = None,
missing_utf8_is_empty_string: bool = False,
ignore_errors: bool = False,
try_parse_dates: bool = False,
n_threads: int | None = None,
infer_schema_length: int | None = N_INFER_DEFAULT,
batch_size: int = 50_000,
n_rows: int | None = None,
encoding: CsvEncoding = "utf8",
low_memory: bool = False,
rechunk: bool = True,
skip_rows_after_header: int = 0,
row_index_name: str | None = None,
row_index_offset: int = 0,
sample_size: int = 1024,
eol_char: str = "\n",
new_columns: Sequence[str] | None = None,
raise_if_empty: bool = True,
truncate_ragged_lines: bool = False,
):
path = normalize_filepath(source)
dtype_list: Sequence[tuple[str, PolarsDataType]] | None = None
dtype_slice: Sequence[PolarsDataType] | None = None
if dtypes is not None:
if isinstance(dtypes, dict):
dtype_list = []
for k, v in dtypes.items():
dtype_list.append((k, py_type_to_dtype(v)))
elif isinstance(dtypes, Sequence):
dtype_slice = dtypes
else:
msg = "`dtypes` arg should be list or dict"
raise TypeError(msg)
processed_null_values = _process_null_values(null_values)
projection, columns = parse_columns_arg(columns)
self._reader = PyBatchedCsv.new(
infer_schema_length=infer_schema_length,
chunk_size=batch_size,
has_header=has_header,
ignore_errors=ignore_errors,
n_rows=n_rows,
skip_rows=skip_rows,
projection=projection,
separator=separator,
rechunk=rechunk,
columns=columns,
encoding=encoding,
n_threads=n_threads,
path=path,
overwrite_dtype=dtype_list,
overwrite_dtype_slice=dtype_slice,
low_memory=low_memory,
comment_prefix=comment_prefix,
quote_char=quote_char,
null_values=processed_null_values,
missing_utf8_is_empty_string=missing_utf8_is_empty_string,
try_parse_dates=try_parse_dates,
skip_rows_after_header=skip_rows_after_header,
row_index=parse_row_index_args(row_index_name, row_index_offset),
sample_size=sample_size,
eol_char=eol_char,
raise_if_empty=raise_if_empty,
truncate_ragged_lines=truncate_ragged_lines,
)
self.new_columns = new_columns
def next_batches(self, n: int) -> list[DataFrame] | None:
"""
Read `n` batches from the reader.
These batches will be parallelized over the available threads.
Parameters
----------
n
Number of chunks to fetch; ideally this is >= number of threads.
Examples
--------
>>> reader = pl.read_csv_batched(
... "./tpch/tables_scale_100/lineitem.tbl",
... separator="|",
... try_parse_dates=True,
... ) # doctest: +SKIP
>>> reader.next_batches(5) # doctest: +SKIP
Returns
-------
list of DataFrames
"""
batches = self._reader.next_batches(n)
if batches is not None:
if self.new_columns:
return [
_update_columns(wrap_df(df), self.new_columns) for df in batches
]
else:
return [wrap_df(df) for df in batches]
return None