我的解决方案是在启动和运行中找到组内的独特模式。但正如你所看到的,我正在加入数据框以达到预期的结果。有没有办法在不使用 join 的情况下实现相同的解决方案。
import polars as pl
# Sample data (replace with your actual data)
data = pl.DataFrame({
"group": ["A", "A", "B", "B", "C", "C", "C","C"],
"value": [1, 1, 2, 2, 3, 3, 4,4]
})
# Group by the "group" column
#############working soltuiom##################
grouped_data = data.group_by("group")
# Find the mode (most frequent value) for each group
mode_values = grouped_data.agg(pl.when(pl.col("value").mode().len()==1)
.then(pl.col("value")\
.mode().first())\
.otherwise(-999)
)
print(mode_values)
#############working soltuiom##################
data=data.join(mode_values,"group","left")
print(data)
C:\Dev\Python3.11\python.exe
C:\Python_Projects\Python_extra_code\code_for_stackoverflow.py
shape: (3, 2)
┌───────┬───────┐
│ group ┆ value │
│ --- ┆ --- │
│ str ┆ i64 │
╞═══════╪═══════╡
│ C ┆ -999 │
│ A ┆ 1 │
│ B ┆ 2 │
└───────┴───────┘
shape: (8, 3)
┌───────┬───────┬─────────────┐
│ group ┆ value ┆ value_right │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═══════╪═══════╪═════════════╡
│ A ┆ 1 ┆ 1 │
│ A ┆ 1 ┆ 1 │
│ B ┆ 2 ┆ 2 │
│ B ┆ 2 ┆ 2 │
│ C ┆ 3 ┆ -999 │
│ C ┆ 3 ┆ -999 │
│ C ┆ 4 ┆ -999 │
│ C ┆ 4 ┆ -999 │
└───────┴───────┴─────────────┘
Process finished with exit code 0
这个问题是在多个组中继续查找模式,如果没有唯一模式则返回 null 让我知道是否可以在旧解决方案中回答同样的问题。我会把这个删掉。