每次出现空值时,如何通过对列的其余部分进行采样以获得唯一值,从而在DataFrame
中实现fill_null
?
例如:假设我有这个DataFrame
:
>>> daf=pl.DataFrame({"a":[1,2, None, None, 5, 6, None, None, None, 10], "b":[None, "two", "three", None, "five", "six", "seven", None, "nine", "ten"]})
>>> daf
shape: (10, 2)
┌──────┬───────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ str │
╞══════╪═══════╡
│ 1 ┆ null │
│ 2 ┆ two │
│ null ┆ three │
│ null ┆ null │
│ 5 ┆ five │
│ 6 ┆ six │
│ null ┆ seven │
│ null ┆ null │
│ null ┆ nine │
│ 10 ┆ ten │
└──────┴───────┘
我想通过对列的其余部分进行采样来填充所有列中的空值.例如,"a"中的空值应该从[1,2,5,6,10]中获得随机值,而"b"中的空值应该从["2","3","5","6","7","9","10"中获得随机值.但a中不应该有str
,b中也不应该有i64
.并且用于填充空值的值对于列中的每个空值都不应该相同.
我可以通过使用标准的Pythonfor
循环遍历列来做到这一点:
>>> for c in daf.columns:
... repl=daf[c].drop_nulls().sample(daf[c].len(), with_replacement=True)
... daf=daf.with_columns(pl.col(c).fill_null(repl))
...
>>> daf
shape: (10, 2)
┌─────┬───────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪═══════╡
│ 1 ┆ two │
│ 2 ┆ two │
│ 1 ┆ three │
│ 2 ┆ six │
│ 5 ┆ five │
│ 6 ┆ six │
│ 5 ┆ seven │
│ 10 ┆ two │
│ 5 ┆ nine │
│ 10 ┆ ten │
└─────┴───────┘
但我试图弄清楚如何使用表达式来做这件事,但我无法做到.有没有一种更简洁的方式来实现这一点,使用Polars表达式语法?