如何在极坐标数据帧上应用冻结集?

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

我有一个 pandas 数据框:

df_names = pd.DataFrame({'last_name':['Williams','Henry','XYX','Smith','David','Freeman','Walter','Test_A'],
                        'first_name':['Henry','Williams','ABC','David','Smith','Walter','Freeman','Test_B']})

enter image description here

在这里,我在

last_name
first_name
列上应用了冻结集,以查看名称是否互换,即 williams henry、henry williams。

df_names[['last_name','first_name']].apply(frozenset,axis=1)

enter image description here

这里在 Polars 数据帧上需要相同类型的实现。如何完成?

enter image description here

python python-polars
2个回答
4
投票

正如 @ritchie46 提到的,您需要避免将 Python 对象(如 freezesets)嵌入到 Polars DataFrame 中。 性能不好,

object
类型的列功能有限。

这里有一个 Polars 算法,它的性能非常好,可以满足您的需求。

(
    df_names
    .with_columns(
        pl.concat_list(
            pl.col("first_name").str.replace_all(r'\s','').str.to_uppercase(),
            pl.col("last_name").str.replace_all(r'\s','').str.to_uppercase(),
        )
        .list.sort()
        .list.join('|')
        .alias('name_key')
    )
    .filter(pl.len().over('name_key') > 1)
)
shape: (6, 3)
┌───────────┬────────────┬────────────────┐
│ last_name ┆ first_name ┆ name_key       │
│ ---       ┆ ---        ┆ ---            │
│ str       ┆ str        ┆ str            │
╞═══════════╪════════════╪════════════════╡
│ Williams  ┆ Henry      ┆ HENRY|WILLIAMS │
│ Henry     ┆ Williams   ┆ HENRY|WILLIAMS │
│ Smith     ┆ David      ┆ DAVID|SMITH    │
│ David     ┆ Smith      ┆ DAVID|SMITH    │
│ Freeman   ┆ Walter     ┆ FREEMAN|WALTER │
│ Walter    ┆ Freeman    ┆ FREEMAN|WALTER │
└───────────┴────────────┴────────────────┘

为了帮助匹配,我已将名称全部转换为大写并消除了空格。 (如果您觉得没有用,可以删除它。)


0
投票

dfl_names.apply
docs)就可以了。您需要将
frozenset
包裹在
tuple
中。

© www.soinside.com 2019 - 2024. All rights reserved.