Best way to get percentage counts in Polars

Viewed 53

I frequently need to calculate the percentage counts of a variable. For example for the dataframe below

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

I want to return a dataframe like this:

person percent
a 0.667
b 0.333

What I have been doing is the following, but I can't help but think there must be a more efficient / polars way to do this

n_rows = len(df)

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

polars.count will help here. When called without arguments, polars.count returns the number of rows in a particular context.

(
    df
    .groupby("person")
    .agg([pl.count().alias("count")])
    .with_column((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      │
└────────┴───────┴───────────────┘
Related