【问题标题】:String match with a list of regex and add column to give the corresponding value if match Python字符串与正则表达式列表匹配,如果匹配 Python,则添加列以给出相应的值
【发布时间】:2020-07-22 22:50:02
【问题描述】:

我很难在一个列 df 中找到字符串匹配,而另一个 df 包含一个正则表达式列表和它自己的正则表达式类型。这是正则表达式 df。

 **Country** |  **Regex**

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

然后,我希望另一个 df 的 Data 列中的值扫描并找到与正则表达式 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 只能匹配字符串类型。但我不知道如何让它扫描列中的整个值并为匹配的正则表达式返回它自己的国家类型。有没有更好的方法来做到这一点?感谢帮助:)

【问题讨论】:

  • 这里没有专家。但是您可以使用 df.astype() 将数据帧转换为字符串,因为它表示数据帧系列是不可变的。

标签: python regex pandas numpy dataframe


【解决方案1】:

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

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 匹配。应该适当调整。

【讨论】:

    猜你喜欢
    • 2013-08-30
    • 2013-10-18
    • 2020-11-29
    • 2011-11-28
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    相关资源
    最近更新 更多