polars 外连接默认空值

polars outer join default null value

https://pola-rs.github.io/polars/py-polars/html/reference/api/polars.DataFrame.join.html

我可以为外连接指定默认的 NULL 值吗?喜欢 0?

join 方法目前没有为 null 设置默认值的选项。但是,有一种简单的方法可以做到这一点。

假设我们有以下数据:

import polars as pl

df1 = pl.DataFrame({"key": ["a", "b", "d"], "var1": [1, 1, 1]})

df2 = pl.DataFrame({"key": ["a", "b", "c"], "var2": [2, 2, 2]})

df1.join(df2, on="key", how="outer")
shape: (4, 3)
┌─────┬──────┬──────┐
│ key ┆ var1 ┆ var2 │
│ --- ┆ ---  ┆ ---  │
│ str ┆ i64  ┆ i64  │
╞═════╪══════╪══════╡
│ a   ┆ 1    ┆ 2    │
├╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ b   ┆ 1    ┆ 2    │
├╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ c   ┆ null ┆ 2    │
├╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ d   ┆ 1    ┆ null │
└─────┴──────┴──────┘

要为 null 值创建不同的值,只需使用:

df1.join(df2, on="key", how="outer").with_column(pl.all().fill_null(0))
shape: (4, 3)
┌─────┬──────┬──────┐
│ key ┆ var1 ┆ var2 │
│ --- ┆ ---  ┆ ---  │
│ str ┆ i64  ┆ i64  │
╞═════╪══════╪══════╡
│ a   ┆ 1    ┆ 2    │
├╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ b   ┆ 1    ┆ 2    │
├╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ c   ┆ 0    ┆ 2    │
├╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ d   ┆ 1    ┆ 0    │
└─────┴──────┴──────┘