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 logic for others len in pivot_longer_spec #1406

Merged
merged 1 commit into from
Sep 23, 2024
Merged
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
29 changes: 16 additions & 13 deletions janitor/polars/pivot_longer.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,24 +150,27 @@ def pivot_longer_spec(
others = [
label for label in spec_columns if label not in {".name", ".value"}
]

if (len(others) == 1) & (spec.get_column(others[0]).dtype == pl.String):
# shortcut that avoids the implode/explode approach - and is faster
# if the requirements are met
# inspired by https://github.com/pola-rs/polars/pull/18519#issue-2500860927
return _pivot_longer_dot_value_string(
df=df,
index=index,
spec=spec,
variable_name=others[0],
)
variable_name = "".join(df_columns + spec_columns)
variable_name = f"{variable_name}_"
if others:
if (len(others) == 1) & (
spec.get_column(others[0]).dtype == pl.String
):
# shortcut that avoids the implode/explode approach - and is faster
# if the requirements are met
# inspired by https://github.com/pola-rs/polars/pull/18519#issue-2500860927
return _pivot_longer_dot_value_string(
df=df,
index=index,
spec=spec,
variable_name=others[0],
)
variable_name = "".join(df_columns + spec_columns)
variable_name = f"{variable_name}_"
dot_value_only = False
expression = pl.struct(others).alias(variable_name)
spec = spec.select(".name", ".value", expression)
else:
variable_name = "".join(df_columns + spec_columns)
variable_name = f"{variable_name}_"
dot_value_only = True
expression = pl.cum_count(".value").over(".value").alias(variable_name)
spec = spec.with_columns(expression)
Expand Down
Loading