我想用类别的出现频率替换类别.我的收件箱很懒惰,目前如果没有对整个数据进行2次传递,然后对一列进行一次传递以获取收件箱的长度,我就无法做到这一点.以下是我的做法:
输入:
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 │
└─────┴──────┴─────┘
所需输出:
shape: (3, 3)
┌─────┬──────┬────────────────────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪══════╪════════════════════╡
│ 1 ┆ 4 ┆ 0.3333333333333333 │
│ 8 ┆ 5 ┆ 0.6666666666666666 │
│ 3 ┆ null ┆ 0.6666666666666666 │
└─────┴──────┴────────────────────┘
转换代码:
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 │
└─────┴──────┴────────────────────┘
如您所见,我收集了2次完整的数据,并且在一列上进行了一次收集.我能做得更好吗?