Skip to content
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

fix(python): on frame-init from generator, initial chunk_size cannot be smaller than infer_schema_length #6541

Merged
merged 1 commit into from
Jan 29, 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
10 changes: 7 additions & 3 deletions py-polars/polars/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -1164,17 +1164,21 @@ def to_frame_chunk(
adaptive_chunk_size = None

df: pli.DataFrame = None # type: ignore[assignment]
chunk_size = max(
(infer_schema_length or 0),
(adaptive_chunk_size or 1000),
)
while True:
values = list(islice(data, adaptive_chunk_size or 1000))
values = list(islice(data, chunk_size))
if not values:
break
frame_chunk = to_frame_chunk(values, original_schema)
if df is None:
df = frame_chunk
if not original_schema:
original_schema = list(df.schema.items())
if not adaptive_chunk_size:
adaptive_chunk_size = n_chunk_elems // len(df.columns)
if chunk_size != adaptive_chunk_size:
chunk_size = adaptive_chunk_size = n_chunk_elems // len(df.columns)
else:
df.vstack(frame_chunk, in_place=True)
n_chunks += 1
Expand Down
4 changes: 2 additions & 2 deletions py-polars/polars/internals/expr/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ def expr_to_lit_or_expr(
expr
Any argument.
str_to_lit
If True string argument `"foo"` will be converted to `lit("foo")`,
If False it will be converted to `col("foo")`
If True string argument `"foo"` will be converted to `lit("foo")`.
If False it will be converted to `col("foo")`.

Returns
-------
Expand Down
8 changes: 8 additions & 0 deletions py-polars/tests/unit/test_df.py
Original file line number Diff line number Diff line change
Expand Up @@ -1265,6 +1265,14 @@ def __iter__(self) -> Iterator[Any]:
assert expected_data == d.row_tuples()
assert expected_schema == list(zip(d.columns(), d.dtypes()))

# ref: issue #6489 (initial chunk_size cannot be smaller than 'infer_schema_length')
df = pl.DataFrame(
data=iter(([{"col": None}] * 1000) + [{"col": ["a", "b", "c"]}]),
infer_schema_length=1001,
)
assert df.schema == {"col": pl.List(pl.Utf8)}
assert df[-2:]["col"].to_list() == [None, ["a", "b", "c"]]

# empty iterator
assert_frame_equal(
pl.DataFrame(data=gen(0), schema=["a", "b", "c", "d"]),
Expand Down