创建一个列以标记其所属组中具有最大值的行。

huangapple go评论56阅读模式
英文:

Create a column to flag rows with largest values of their respective groups

问题

给定一个拥有列 'group' 和 'value' 的 Polars 数据框,创建一个新列 'group_max',以标记哪些记录是其所属组的最大值。

这可以在 Pandas 中相对容易地实现。

在 Polars 中是否有可能在不首先创建一个单独的分组数据框,然后基于 'group' 和 'value' 键将该数据框与原始数据框连接的情况下完成这个任务?

编辑:
以下代码可以实现此目标,但会创建一个中间分组数据框:

grouped = df.groupby('group').agg(pl.col('value').max()).with_columns(pl.lit(1).alias('value'))

df = df.join(grouped, on=['group', 'value'], how='outer')
英文:

Given a polars dataframe with columns 'group' and 'value' create a new column 'group_max' to flag which records are the max of their respective group.

This can be achieved in pandas relatively straightforwardly

https://stackoverflow.com/questions/70051051/column-to-flag-the-most-max-row-of-a-group

Is it possible to do this in polars without first creating a separate grouped dataframe and then joining that dataframe to the original based on the 'group' and 'value' keys?

EDIT:
The following code works but creates an intermediary grouped dataframe

grouped = df.groupby('group').agg(pl.col('value').max()).with_columns(pl.lit(1).alias('value'))

df = df.join(grouped, on = ['group', 'value'], how='outer')

答案1

得分: 1

窗口函数

df = pl.DataFrame(dict(
   group = ["A", "B", "C", "A", "B", "C"], 
   value = [1, 2, 3, 1, 4, 1]
))

df.with_columns(group_max = pl.col("value") == pl.max("value").over("group"))
shape: (6, 3)
┌───────┬───────┬───────────┐
│ group ┆ value ┆ group_max │
│ ---   ┆ ---   ┆ ---       │
│ str   ┆ i64   ┆ bool      │
╞═══════╪═══════╪═══════════╡
│ A     ┆ 1     ┆ true      │
│ B     ┆ 2     ┆ false     │
│ C     ┆ 3     ┆ true      │
│ A     ┆ 1     ┆ true      │
│ B     ┆ 4     ┆ true      │
│ C     ┆ 1     ┆ false     │
└───────┴───────┴───────────┘
英文:

Window functions

df = pl.DataFrame(dict(
   group = ["A", "B", "C", "A", "B", "C"], 
   value = [1, 2, 3, 1, 4, 1]
))

df.with_columns(group_max = pl.col("value") == pl.max("value").over("group"))
shape: (6, 3)
┌───────┬───────┬───────────┐
│ group ┆ value ┆ group_max │
│ ---   ┆ ---   ┆ ---       │
│ str   ┆ i64   ┆ bool      │
╞═══════╪═══════╪═══════════╡
│ A     ┆ 1     ┆ true      │
│ B     ┆ 2     ┆ false     │
│ C     ┆ 3     ┆ true      │
│ A     ┆ 1     ┆ true      │
│ B     ┆ 4     ┆ true      │
│ C     ┆ 1     ┆ false     │
└───────┴───────┴───────────┘

huangapple
  • 本文由 发表于 2023年6月29日 23:33:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定