You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Polars左连接操作中同时保留左右连接键?

在Python Polars中左连接时保留左右两侧连接键的方法

Polars默认用on参数做连接时,会把左右表的连接键合并成一列。如果要同时保留两边的连接键,得让它们在连接时有不同的列名,下面是两种常用的实现方式:

方法一:复制右表连接键为新列后连接

先给右表的连接键复制一份并改名,再执行左连接,这样左表原键和右表的复制键都会保留:

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"],
    }
)

# 给右表的ham列复制一份,命名为ham_right
other_df_with_dup = other_df.with_columns(ham_right=pl.col("ham"))
# 以左表的ham为连接键做左连接
result = df.join(other_df_with_dup, on="ham", how="left")
print(result)

输出结果会包含左表的ham、右表的ham_right,以及其他列:

shape: (3, 5)
┌─────┬─────┬─────┬───────┬──────────┐
│ 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     │
└─────┴─────┴─────┴───────┴──────────┘

方法二:重命名右表连接键后用left_on/right_on指定连接

先把右表的连接键改成新名称,再通过left_on和right_on分别指定左右表的连接字段,连接后两个键会被同时保留:

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"],
    }
)

# 把右表的ham重命名为ham_right
other_df_renamed = other_df.rename({"ham": "ham_right"})
# 指定左表用ham、右表用ham_right做左连接
result = df.join(other_df_renamed, left_on="ham", right_on="ham_right", how="left")
print(result)

输出和方法一完全一致。

目前Polars没有像R dplyr那样的keep=TRUE参数直接一键保留两侧连接键,但上面两种方法操作简单,也能灵活控制列名。

内容的提问来源于stack exchange,提问作者jeremyh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 18:52:48