gpt4 book ai didi

python - Pandas 子字符串搜索过滤器

转载 作者:太空宇宙 更新时间:2023-11-03 14:24:56 25 4
gpt4 key购买 nike

我有一个用例,我需要验证 df 中的每一行并标记它是否正确。验证规则在另一个df中。

Main

col1 col2
0 1 take me home
1 2 country roads
2 2 country roads take
3 4 me home


Rules

col3 col4
0 1 take
1 2 home
2 3 country
3 4 om
4 2 take

如果以下条件与 rules 中的任何行匹配,则 main 中的行将被标记为通过

通过的条件是: col1==col3 并且 col4 是 col2 的子字符串

 Main

col1 col2 result
0 1 take me home Pass
1 2 country roads Fail
2 2 country roads take Pass
3 4 me home Pass

我最初的方法是解析规则 df 并动态创建一个函数,然后运行

    def action_function(row) -> object:
if self.combined_filter()(row): #combined_filter() is the lambda equivalent of Rules df
return success_action(row) #mark as pass
return fail_action(row) #mark as fail

Main["result"] = self.df.apply(action_function, axis=1)

结果证明这非常慢,因为 apply 没有矢量化。主df约300万条,规则df约500条。所需时间约为3小时。

我正在尝试使用 pandas merge 来实现此目的。但合并操作不支持子字符串匹配。我无法按空格或任何其他方式分割单词。

这将用作系统的一部分。所以我不能对任何东西进行硬编码。每次系统启动时,我都需要从 excel 读取 df 。您能建议一种方法吗?

最佳答案

合并然后使用 np.where i.s 应用条件

temp = main.merge(rules,left_on='col1',right_on='col3')
temp['results'] = temp.apply(lambda x : np.where(x['col4'] in x['col2'],'Pass','Fail'),1)

no_dupe_df = temp.drop_duplicates('col2',keep='last').drop(['col3','col4'],1)

col1 col2 results
0 1 take me home Pass
2 2 country roads Fail
4 2 country roads take Pass
5 4 me home Pass

关于python - Pandas 子字符串搜索过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47708345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com