I want to replace the categories with their occurrence frequency. My dataframe is lazy and currently I cannot do it without 2 passes over the entire data and then one pass over a column to get the length of the dataframe. Here is how I am doing it:
Input:
df = pl.DataFrame({"a": [1, 8, 3], "b": [4, 5, None], "c": ["foo", "bar", "bar"]}).lazy()
print(df.collect())
output:
shape: (3, 3)
┌─────┬──────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪══════╪═════╡
│ 1 ┆ 4 ┆ foo │
│ 8 ┆ 5 ┆ bar │
│ 3 ┆ null ┆ bar │
└─────┴──────┴─────┘
Required output:
shape: (3, 3)
┌─────┬──────┬────────────────────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪══════╪════════════════════╡
│ 1 ┆ 4 ┆ 0.3333333333333333 │
│ 8 ┆ 5 ┆ 0.6666666666666666 │
│ 3 ┆ null ┆ 0.6666666666666666 │
└─────┴──────┴────────────────────┘
transformation code:
l = df.select("c").collect().shape[0]
rep = df.group_by("c").len().collect().with_columns(pl.col("len")/l).lazy()
df_out = df.with_context(rep.select(pl.all().name.prefix("context_"))).with_columns(pl.col("c").replace(pl.col("context_c"), pl.col("context_len"))).collect()
print(df_out)
output:
shape: (3, 3)
┌─────┬──────┬────────────────────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪══════╪════════════════════╡
│ 1 ┆ 4 ┆ 0.3333333333333333 │
│ 8 ┆ 5 ┆ 0.6666666666666666 │
│ 3 ┆ null ┆ 0.6666666666666666 │
└─────┴──────┴────────────────────┘
As you can see I am collecting the data 2 times full and there is one collect over a single column. Can I do better?