我有一个 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']})
在这里,我在
last_name
和 first_name
列上应用了冻结集,以查看名称是否互换,即 williams henry、henry williams。
df_names[['last_name','first_name']].apply(frozenset,axis=1)
这里在 Polars 数据帧上需要相同类型的实现。如何完成?
正如 @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 │
└───────────┴────────────┴────────────────┘
为了帮助匹配,我已将名称全部转换为大写并消除了空格。 (如果您觉得没有用,可以删除它。)