熊猫-将一列字符串与一列正则表达式匹配

时间:2020-04-29 13:23:25

标签: pandas dataframe

问题:我有两个数据框-一个带有一堆未规范化的产品标题,另一个带有一堆与规范化产品标题相关的正则表达式。我需要将非规范化标题与一些与规范化标题相关联的正则表达式进行匹配。 使用下面的示例数据应该更有意义。

第一个数据帧(原始标题):

|   | Title                                          | Release Date |
|---|------------------------------------------------|--------------|
| 1 | Apple iPad Air (3rd generation) - 64GB         | 01/01/20     |
| 2 | Philips Hue White Ambiance A19 LED Smart Bulbs | 08/12/20     |
| 3 | Powerbeats Pro Totally Wireless Earphones      | 06/20/19     |

第二个数据帧(regex_titles):

|   | Regex                                                 | Manufacturer | Model                   |
|---|-------------------------------------------------------|--------------|-------------------------|
| 1 | /ipad\s?air(?=.*(\b3\b|3rd\s?gen|2019))|\bair\s?3\b/i | Apple        | iPad Air (2019)         |
| 2 | /hue(?=.*cher)/i                                      | Philips      | Hue White Ambiance Cher |
| 3 | /powerbeats\s?pro/i                                   | Beats        | Powerbeats Pro          |

这个想法是将每个标题放在raw_titles中,并通过regex_titles中的所有值运行它,以查看是否存在匹配项。完成此操作后,raw_titles应该具有两个附加列,Manufacturer和Model,它们与它们匹配的regex_titles系列相对应(如果没有匹配,它将保持为空。

然后,决赛桌将如下所示:

|   | Title                                          | Release Date | Manufacturer | Model           |
|---|------------------------------------------------|--------------|--------------|-----------------|
| 1 | Apple iPad Air (3rd generation) - 64GB         | 01/01/20     | Apple        | iPad Air (2019) |
| 2 | Philips Hue White Ambiance A19 LED Smart Bulbs | 08/12/20     |              |                 |
| 3 | Powerbeats Pro Totally Wireless Earphones      | 06/12/19     | Beats        | Powerbeats Pro  |

1 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点,但是最简单的方法是测试每个标题上的每个正则表达式并返回找到的第一个匹配项。首先,我们将定义一个函数,该函数将返回两个值:regex行的制造商和模型(如果匹配),否则返回两个None

def find_match(title_row):
    for _, regex_row in regex_titles.iterrows():
        if re.search(regex_row['Regex'], title_row['Title']):
            return [regex_row['Manufacturer'], regex_row['Model']]
    return  [None, None]

然后,我们将函数应用于标题数据框,并将输出保存到两个新列,制造商和型号:

raw_titles[['Manufacturer', 'Model']] = raw_titles.apply(find_match, axis=1, result_type='broadcast')

                                            Title Release Date Manufacturer            Model
0          Apple iPad Air (3rd generation) - 64GB     01/01/20        Apple  iPad Air (2019)
1  Philips Hue White Ambiance A19 LED Smart Bulbs     08/12/20         None             None
2       Powerbeats Pro Totally Wireless Earphones     06/20/19        Beats   Powerbeats Pro

一个复杂的问题是,您必须将perl正则表达式转换为python regex格式:

perl:/powerbeats\s?pro/i-> python:(?i)powerbeats\s?pro

它们基本相同,但有一些细微的差别。 Here's the reference.