字符串与正则表达式列表匹配,如果匹配Python

时间:2020-04-10 07:47:08

标签: python regex pandas numpy dataframe

我很难在一列df中找到与正则表达式及其自己的正则表达式类型列表匹配的另一列df中的字符串。这是regex df。

 **Country** |  **Regex**

     CN      |  ^\w{8,25}$
     BE      |  ^BE[0-9]{10}
     AT      |  ^ATU[0-9]{8}

然后,我希望另一个df的“数据”列中的值进行扫描,并找到与正则表达式df的任何匹配项,并返回在找到匹配的正则表达式的国家/地区类型。这是我想要的输出(“建议”列)。需要它给我建议与正则表达式匹配的国家/地区类型。

 **Data**   | **Suggestion**            **Data**   | **Suggestion** 

 BE135688   |              ---->        BE135688   |   BE   
 78567899   |                           78567899   |   CN
 AT5678899  |                           AT5678899  |   AT

这是我尝试过的,

df['Data'].str.match(df_regex.Regex)

但是我得到了这个错误,

TypeError: ("'Series' objects are mutable, thus they cannot be hashed", 'occurred at index 271179')

我知道str.match只能与字符串类型匹配。但是我不知道如何使它扫描列中的整个值并为匹配的正则表达式返回其自己的国家类型。有什么更好的方法吗?感谢帮助:)

1 个答案:

答案 0 :(得分:0)

一种选择是遍历所有正则表达式,每次匹配时,在建议中添加相应的国家/地区。这是一个示例*:

import pandas as pd
df_regex = pd.DataFrame({'Country': ['CN', 'BE', 'AT'],
             'Regex': ['^\w{8,25}$', '^BE[0-9]{10}', '^AT[0-9]{7}']})
df = pd.DataFrame({'Data': ['BE135688', '78567899', 'AT5678899']})
regex_map = dict(zip(df_regex.Regex, df_regex.Country))
def country_suggestions(row):
    matches = []
    for reg in regex_map:
        if re.search(reg, row):
            matches.append(regex_map[reg])
    return ', '.join(matches)

df['Suggestions'] = df['Data'].apply(country_suggestions)
print(df)

这是输出:

        Data Suggestions
0   BE135688          CN
1   78567899          CN
2  AT5678899      CN, AT

*注意,我已将正则表达式^ATU[0-9]{8}更改为^AT[0-9]{7},因此它实际上与值AT5678899相匹配。应该适当调整。