Skip to content

sort in add expr in group_by context propagates to other column #24504

@kdn36

Description

@kdn36

Checks

  • I have checked that this issue has not already been reported.
  • I have confirmed this bug exists on the latest version of Polars.

Reproducible example

import polars as pl

df = pl.DataFrame({"g": [10, 10, 10], "a": [2, 1, 3], "b": [100, 200, 300]})

# NotAgg, NotAgg
out = df.group_by("g").agg(pl.col("a").sort() + pl.col("b"))
print(out)

# more info
print(df)
out = df.group_by("g").agg(
    [
        pl.col("a").sort(),
        pl.col("b"),
        (pl.col("a").sort() + pl.col("b")).alias("add"),
    ]
)
print(out)

Log output

shape: (1, 2)
┌─────┬─────────────────┐
│ g   ┆ a               │
│ --- ┆ ---             │
│ i64 ┆ list[i64]       │
╞═════╪═════════════════╡
│ 10  ┆ [201, 102, 303] │
└─────┴─────────────────┘
shape: (3, 3)
┌─────┬─────┬─────┐
│ g   ┆ a   ┆ b   │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 10  ┆ 2   ┆ 100 │
│ 10  ┆ 1   ┆ 200 │
│ 10  ┆ 3   ┆ 300 │
└─────┴─────┴─────┘
shape: (1, 4)
┌─────┬───────────┬─────────────────┬─────────────────┐
│ g   ┆ a         ┆ b               ┆ add             │
│ --- ┆ ---       ┆ ---             ┆ ---             │
│ i64 ┆ list[i64] ┆ list[i64]       ┆ list[i64]       │
╞═════╪═══════════╪═════════════════╪═════════════════╡
│ 10  ┆ [1, 2, 3] ┆ [100, 200, 300] ┆ [201, 102, 303] │
└─────┴───────────┴─────────────────┴─────────────────┘

Issue description

Sorting one column in the argument of a binary expression propagates to the other column.

Code insight: groups mismatch in all NotAggregated states in BinaryExpr.

Expected behavior

Sort should be contained to the appropriate expression.

shape: (1, 2)
┌─────┬─────────────────┐
│ g   ┆ a               │
│ --- ┆ ---             │
│ i64 ┆ list[i64]       │
╞═════╪═════════════════╡
│ 10  ┆ [101, 202, 303] │
└─────┴─────────────────┘

Installed versions

--------Version info---------
Polars:              1.33.1
Index type:          UInt32
Platform:            Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39
Python:              3.13.5 (main, Jul 18 2025, 09:47:32) [GCC 13.3.0]
LTS CPU:             False

Metadata

Metadata

Assignees

Labels

A-opsArea: operationsP-highPriority: highacceptedReady for implementationbugSomething isn't workingpythonRelated to Python Polars

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions