使用 Python Polars 数据框库执行左连接时,是否有办法保留左连接键和右连接键?目前似乎只保留了左连接键,但右连接键被删除了。
请参阅下面的示例代码:
import polars as pl
df = pl.DataFrame(
{
"foo": [1, 2, 3],
"bar": [6.0, 7.0, 8.0],
"ham": ["a", "b", "c"],
}
)
other_df = pl.DataFrame(
{
"apple": ["x", None, "z"],
"ham": ["a", "b", "d"],
}
)
df.join(other_df, on="ham", how="left")
在其他数据操作库中这是可能的,例如使用 R dplyr 库,您可以执行以下操作,甚至在标准 SQL 中,我们可以在
SELECT
子句中访问右连接键。
library(dplyr)
df <- data.frame(
foo = c(1, 2, 3),
bar = c(6.0, 7.0, 8.0),
ham = c("a", "b", "c")
)
other_df <- data.frame(
apple = c("x", NA, "z"),
ham = c("a", "b", "d")
)
df %>%
left_join(other_df, by = c("ham" = "ham"), suffix = c("", "_right"), keep = TRUE)
一个可能的选择:
out = (
df.join(
other_df.with_columns(pl.col("ham").alias("ham_right")),
on="ham", how="left"
)
)
输出:
print(out)
┌─────┬─────┬─────┬───────┬───────────┐
│ foo ┆ bar ┆ ham ┆ apple ┆ ham_right │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str ┆ str ┆ str │
╞═════╪═════╪═════╪═══════╪═══════════╡
│ 1 ┆ 6.0 ┆ a ┆ x ┆ a │
│ 2 ┆ 7.0 ┆ b ┆ null ┆ b │
│ 3 ┆ 8.0 ┆ c ┆ null ┆ null │
└─────┴─────┴─────┴───────┴───────────┘