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

.first behind .sort_by.slice gets wrong result. #18231

Closed
2 tasks done
PierXuY opened this issue Aug 16, 2024 · 2 comments · Fixed by #18603
Closed
2 tasks done

.first behind .sort_by.slice gets wrong result. #18231

PierXuY opened this issue Aug 16, 2024 · 2 comments · Fixed by #18603
Assignees
Labels
accepted Ready for implementation bug Something isn't working needs triage Awaiting prioritization by a maintainer python Related to Python Polars

Comments

@PierXuY
Copy link

PierXuY commented Aug 16, 2024

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(
    {"name": list("abcdef"), "age": [21, 31, 32, 53, 45, 26], "country": list("AABBBC")}
)
print(df)

out1 = df.group_by("country").agg(
    pl.col("name").sort_by("age").slice(2, 1)
).sort("country")
print(out1)

out2 = df.group_by("country").agg(
    pl.col("name").sort_by("age").slice(2,1).first()  # only add .first(), but get wrong result.

).sort("country")
print(out2)

Log output

shape: (6, 3)
┌──────┬─────┬─────────┐
│ name ┆ age ┆ country │
│ ---  ┆ --- ┆ ---     │
│ str  ┆ i64 ┆ str     │
╞══════╪═════╪═════════╡
│ a    ┆ 21  ┆ A       │
│ b    ┆ 31  ┆ A       │
│ c    ┆ 32  ┆ B       │
│ d    ┆ 53  ┆ B       │
│ e    ┆ 45  ┆ B       │
│ f    ┆ 26  ┆ C       │
└──────┴─────┴─────────┘
shape: (3, 2)
┌─────────┬───────────┐
│ country ┆ name      │
│ ---     ┆ ---       │
│ str     ┆ list[str] │
╞═════════╪═══════════╡
│ A       ┆ []        │
│ B       ┆ ["d"]     │
│ C       ┆ []        │
└─────────┴───────────┘
shape: (3, 2)
┌─────────┬──────┐
...
│ A       ┆ null │
│ B       ┆ e    │
│ C       ┆ null │
└─────────┴──────┘

Issue description

The result of .first() should be d in list of out1, not e.

Expected behavior

get correctly result

Installed versions

--------Version info---------
Polars:               1.5.0
Index type:           UInt32
Platform:             Windows-10-10.0.22631-SP0
Python:               3.10.11 (tags/v3.10.11:7d4cc5a, Apr  5 2023, 00:38:17) [MSC v.1929 64 bit (AMD64)]

----Optional dependencies----
adbc_driver_manager:  1.1.0
cloudpickle:          3.0.0
connectorx:           0.3.3
deltalake:            0.19.0
fastexcel:            0.11.5
fsspec:               2024.6.1
gevent:               24.2.1
great_tables:         0.10.0
hvplot:               0.10.0
matplotlib:           3.9.2
nest_asyncio:         1.6.0
numpy:                2.0.1
openpyxl:             3.1.5
pandas:               2.2.2
pyarrow:              17.0.0
pydantic:             2.8.2
pyiceberg:            0.7.0
sqlalchemy:           2.0.32
torch:                <not installed>
xlsx2csv:             0.8.3
xlsxwriter:           3.2.0
@PierXuY PierXuY added bug Something isn't working needs triage Awaiting prioritization by a maintainer python Related to Python Polars labels Aug 16, 2024
@PierXuY
Copy link
Author

PierXuY commented Sep 4, 2024

Is this a bug?

@cmdlineluser
Copy link
Contributor

I believe so.

If we change the example slightly, we actually get values from the wrong group.

df = pl.DataFrame(
    {"name": list("abcdef"), "age": [31, 21, 32, 53, 45, 26], "country": list("AABBBC")}
)

df.group_by("country", maintain_order=True).agg(
    sort_by = pl.col("name").sort_by("age"),
    x =  pl.col("name").sort_by("age").slice(0, 1).first(),
    y =  pl.col("name").sort_by("age").slice(1, 1).first(),
    z =  pl.col("name").sort_by("age").slice(2, 1).first()
)
# shape: (6, 3)
# ┌──────┬─────┬─────────┐
# │ name ┆ age ┆ country │
# │ ---  ┆ --- ┆ ---     │
# │ str  ┆ i64 ┆ str     │
# ╞══════╪═════╪═════════╡
# │ a    ┆ 31  ┆ A       │
# │ b    ┆ 21  ┆ A       │
# │ c    ┆ 32  ┆ B       │
# │ d    ┆ 53  ┆ B       │
# │ e    ┆ 45  ┆ B       │
# │ f    ┆ 26  ┆ C       │
# └──────┴─────┴─────────┘
# shape: (3, 5)
# ┌─────────┬─────────────────┬─────┬──────┬──────┐
# │ country ┆ sort_by         ┆ x   ┆ y    ┆ z    │
# │ ---     ┆ ---             ┆ --- ┆ ---  ┆ ---  │
# │ str     ┆ list[str]       ┆ str ┆ str  ┆ str  │
# ╞═════════╪═════════════════╪═════╪══════╪══════╡
# │ A       ┆ ["b", "a"]      ┆ b   ┆ c    ┆ null │ # <- value `c` belongs to country `B`
# │ B       ┆ ["c", "e", "d"] ┆ c   ┆ d    ┆ e    │ # <- wrong order
# │ C       ┆ ["f"]           ┆ f   ┆ null ┆ null │
# └─────────┴─────────────────┴─────┴──────┴──────┘

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
accepted Ready for implementation bug Something isn't working needs triage Awaiting prioritization by a maintainer python Related to Python Polars
Projects
Archived in project
Development

Successfully merging a pull request may close this issue.

4 participants