在 Polars 中获取百分比计数的最佳方法

2023-12-08

我经常需要计算变量的百分比计数。例如下面的数据框

df = pl.DataFrame({"person": ["a", "a", "b"], 
                   "value": [1, 2, 3]})

我想返回这样的数据框:

person percent
a 0.667
b 0.333

我一直在做的事情如下,但我忍不住认为必须有一种更有效/极地的方法来做到这一点

n_rows = len(df)

(   
    df
    .with_column(pl.lit(1)
    .alias('percent'))
    .groupby('person')
    .agg([pl.sum('percent') / n_rows])
)

polars.count会在这里提供帮助。当不带参数调用时,polars.count返回特定上下文中的行数。

(
    df
    .groupby("person")
    .agg([pl.count().alias("count")])
    .with_columns((pl.col("count") / pl.sum("count")).alias("percent_count"))
)
shape: (2, 3)
┌────────┬───────┬───────────────┐
│ person ┆ count ┆ percent_count │
│ ---    ┆ ---   ┆ ---           │
│ str    ┆ u32   ┆ f64           │
╞════════╪═══════╪═══════════════╡
│ a      ┆ 2     ┆ 0.666667      │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ b      ┆ 1     ┆ 0.333333      │
└────────┴───────┴───────────────┘
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Polars 中获取百分比计数的最佳方法 的相关文章

随机推荐