Ambiguous results when apply 'filter' in Polars groupby context
00:33 19 Feb 2023

The code below when run multiple times, gives me two different possible results.

import polars as pl

df = pl.DataFrame(
    {
        "day": [2, 2, 2, 2, 2, 2, 1, 1],
        "y": [4, 5, 8, 7, 9, None, None, None],
        "x": [1, 2, 3, 4, 5, 6, 1, 2],
    }

)

xcol = "x"
ycol = "y"
f = pl.col(ycol).is_not_null() & pl.col(xcol).is_not_null()

df.groupby("day").agg(
    (pl.col(xcol) - pl.col(xcol).filter(f).mean()).filter(f).sum().alias("filered_sum")
)

The two results returned to me are

day filtered_sum
1   null
2   -3.0

day filtered_sum
2   0.0
1   null

And, the result I expect to have is

day filtered_sum
2   0.0
1   null

Any idea what is going on here? What could be the reason for such non-determinate behavior?

python python-polars