Pandas substring搜索过滤器

时间:2017-12-08 05:35:12

标签: python pandas dataframe

我有一个用例,我需要验证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

如果以下条件与main

中的任何行匹配,则rules中的行会被标记为通过

传球的条件是:     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)

由于应用不是矢量化,因此结果非常慢。主df约为300万,规则df约为500个条目。所需时间约为3小时。

我正在尝试使用pandas merge。但合并操作不支持子字符串匹配。我不能用空格或任何东西来分词。

这将用作系统的一部分。所以我不能硬编码。每次系统启动时我都需要从excel中读取df。 你能为此建议一个方法吗?

1 个答案:

答案 0 :(得分:1)

合并,然后使用np.where即

应用条件
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
相关问题