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

Allow using .map_elements(fn_which_returns_a_2_tuple, return_dtype=pl.Struct(...)) #20352

Open
DeflateAwning opened this issue Dec 18, 2024 · 0 comments
Labels
enhancement New feature or an improvement of an existing feature

Comments

@DeflateAwning
Copy link
Contributor

DeflateAwning commented Dec 18, 2024

Request: Allow using .map_elements(fn_which_returns_a_2_tuple, return_dtype=pl.Struct({'field0': pl.String, 'field1': pl.String}))

Description

It would be neat if the following worked!

from typing import Any
import polars as pl

def test_tuple_return_to_struct() -> None:
    df = pl.DataFrame({"id": [1, 2, 3], "value": ["a", "b", "c"]})

    def create_tuple(value: Any) -> tuple[str, str]:
        """Arbitrary function which turns a fixed-length tuple."""
        return f"prefix_{value}", f"suffix_{value}"

    # Attempt to force the fixed-length tuple into a struct.
    df_out = df.with_columns(
        pl.col("value")
        .map_elements(
            create_tuple, return_dtype=pl.Struct({"field0": pl.String, "field1": pl.String})
        )
        .alias("struct_column")
    )

    assert df_out["struct_column"].to_list() == [
        {"field0": "prefix_a", "field1": "suffix_a"},
        {"field0": "prefix_b", "field1": "suffix_b"},
        {"field0": "prefix_c", "field1": "suffix_c"},
    ]

Currently, it errors like:

polars.exceptions.SchemaError: expected output type 'Struct([Field { name: "field0", dtype: String }, Field { name: "field1", dtype: String }])', got 'List(String)'; set `return_dtype` to the proper datatype
@DeflateAwning DeflateAwning added the enhancement New feature or an improvement of an existing feature label Dec 18, 2024
@DeflateAwning DeflateAwning changed the title Allow using map_elements(fn_which_returns_a_2_tuple, return_dtype=pl.Struct({'field0': pl.String, 'field1': pl.String}) Allow using map_elements(fn_which_returns_a_2_tuple, return_dtype=pl.Struct(...) Dec 18, 2024
@DeflateAwning DeflateAwning changed the title Allow using map_elements(fn_which_returns_a_2_tuple, return_dtype=pl.Struct(...) Allow using .map_elements(fn_which_returns_a_2_tuple, return_dtype=pl.Struct(...)) Dec 18, 2024
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
Projects
None yet
Development

No branches or pull requests

1 participant