Polars 中的 Pandas 合并功能

问题描述 投票:0回答:2

我想合并两个 Polars DataFrame(可能在多个列上),并且用于合并的列不重复。

当前行为:

>>> a 
shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1   ┆ 1   │
│ 2   ┆ 2   │
│ 3   ┆ 3   │
└─────┴─────┘
>>> b
shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 3   ┆ 3   │
│ 4   ┆ 4   │
│ 5   ┆ 5   │
└─────┴─────┘
>>> a.join(b, how='outer', on='a')
shape: (5, 4)
┌──────┬──────┬─────────┬─────────┐
│ a    ┆ b    ┆ a_right ┆ b_right │
│ ---  ┆ ---  ┆ ---     ┆ ---     │
│ i64  ┆ i64  ┆ i64     ┆ i64     │
╞══════╪══════╪═════════╪═════════╡
│ 3    ┆ 3    ┆ 3       ┆ 3       │
│ null ┆ null ┆ 4       ┆ 4       │
│ null ┆ null ┆ 5       ┆ 5       │
│ 1    ┆ 1    ┆ null    ┆ null    │
│ 2    ┆ 2    ┆ null    ┆ null    │
└──────┴──────┴─────────┴─────────┘

我想要什么:

>>> a 
shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1   ┆ 1   │
│ 2   ┆ 2   │
│ 3   ┆ 3   │
└─────┴─────┘
>>> b
shape: (3, 2)
┌─────┬─────┐
│ a   ┆ b   │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 3   ┆ 3   │
│ 4   ┆ 4   │
│ 5   ┆ 5   │
└─────┴─────┘
>>> <what command goes here>
shape: (5, 3)
┌─────┬──────┬──────┐
│ a   ┆ b_x  ┆ b_y  │
│ --- ┆ ---  ┆ ---  │
│ i64 ┆ f64  ┆ f64  │
╞═════╪══════╪══════╡
│ 1   ┆ 1.0  ┆ null │
│ 2   ┆ 2.0  ┆ null │
│ 3   ┆ 3.0  ┆ 3.0  │
│ 4   ┆ null ┆ 4.0  │
│ 5   ┆ null ┆ 5.0  │
└─────┴──────┴──────┘

我想要这种行为,因为我有大型 DataFrame,我想将其合并到多个列上。一种可能有效的方法是以某种方式合并生成的键列,然后删除重复的列,但这似乎很麻烦。

python pandas merge python-polars
2个回答
1
投票

how
 上的 
pl.DataFrame.join
参数设置为
"outer_coalesce"
会给出预期的数据帧。

来自文档:

与“外部”相同,但合并关键列

a.join(b, on="a", how="outer_coalesce").sort("a")
shape: (5, 3)
┌─────┬──────┬─────────┐
│ a   ┆ b    ┆ b_right │
│ --- ┆ ---  ┆ ---     │
│ i64 ┆ i64  ┆ i64     │
╞═════╪══════╪═════════╡
│ 1   ┆ 1    ┆ null    │
│ 2   ┆ 2    ┆ null    │
│ 3   ┆ 3    ┆ 3       │
│ 4   ┆ null ┆ 4       │
│ 5   ┆ null ┆ 5       │
└─────┴──────┴─────────┘

0
投票
a.join(b, how='outer_coalesce', on='a')

┌─────┬──────┬─────────┐
│ a   ┆ b    ┆ b_right │
│ --- ┆ ---  ┆ ---     │
│ i64 ┆ i64  ┆ i64     │
╞═════╪══════╪═════════╡
│ 3   ┆ 3    ┆ 3       │
│ 4   ┆ null ┆ 4       │
│ 5   ┆ null ┆ 5       │
│ 2   ┆ 2    ┆ null    │
│ 1   ┆ 1    ┆ null    │
└─────┴──────┴─────────┘
© www.soinside.com 2019 - 2024. All rights reserved.