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

feat(python): support DataFrame init from generators #5424

Merged
merged 1 commit into from
Nov 4, 2022
Merged

feat(python): support DataFrame init from generators #5424

merged 1 commit into from
Nov 4, 2022

Conversation

alexander-beedie
Copy link
Collaborator

@alexander-beedie alexander-beedie commented Nov 4, 2022

Expands on #5411, adding support for initialising DataFrames from generators (in either orientation). Can even init from a generator of generators now, if that floats your boat ;)

from random import randint
import polars as pl

def gendata(n_rows, n_cols):
    for i in range(n_rows):
        yield (randint(-100,100) for j in range(n_cols))

pl.DataFrame( gendata(5,3), columns=["x","y","z"] )

# shape: (5, 3)
# ┌─────┬─────┬─────┐
# │ x   ┆ y   ┆ z   │
# │ --- ┆ --- ┆ --- │
# │ i64 ┆ i64 ┆ i64 │
# ╞═════╪═════╪═════╡
# │ 60  ┆ 26  ┆ -69 │
# │ 3   ┆ -58 ┆ 19  │
# │ -49 ┆ 76  ┆ 63  │
# │ 44  ┆ -93 ┆ -71 │
# │ 42  ┆ -2  ┆ 58  │
# └─────┴─────┴─────┘

It's a bit more complex than the previous Series update, as you don't necessarily know in advance how many columns you have; if that can't be inferred (eg: no 'columns' param) then the initial chunk is limited to 1000 rows - all subsequent updates can then target taking chunks of 1,000,000 elements, which initial testing shows seems to be reasonable, but we can probably optimise further based on the underlying/inferred schema.

Also:

  • Calls to PyDataFrame.read_rows make better use of the relatively new schema override param, to avoid post-init casts.
  • Fixed Series init from generators that return no data.
  • Better generator type-detection.

@github-actions github-actions bot added enhancement New feature or an improvement of an existing feature python Related to Python Polars labels Nov 4, 2022
@ritchie46 ritchie46 merged commit 041143e into pola-rs:master Nov 4, 2022
@alexander-beedie alexander-beedie deleted the dataframe-init-from-generator branch November 4, 2022 19:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or an improvement of an existing feature python Related to Python Polars
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants