【问题标题】:Match list of strings in pandas column with RegEx将 pandas 列中的字符串列表与 RegEx 匹配
【发布时间】:2020-09-09 01:55:02
【问题描述】:

问题:从字符串列表中找到所有明确包含子字符串的名称并返回该字符串。

我有一个熊猫系列,比如:

231                richard occult (new earth)
6886                     bedivere (new earth)
705              arthur pendragon (new earth)
567     franklin delano roosevelt (new earth)
1468                     lancelot (new earth)
                        ...                  
6891                  nadine west (new earth)
6892               warren harding (new earth)
6893             william harrison (new earth)
6894             william mckinley (new earth)
6895                       mookie (new earth)
6896                     Superboy (new earth)

我有一个希望与每个名称匹配的特定子字符串的列表,即:

boy_names = ['Mr.', 'Boy', 'Man', 'Lord', 'King', 
            'Brother', 'Sir', 'Prince', 'Father', 'Lad',
            'Baron', 'He-',' He' 'Son', 'Duke','Son','Dad', 'Senior',
            'Junior', 'Master']

所需输出:Superboy

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    我找到了一个返回匹配项的答案,但不是整个字符串。

    def match(frame):
        result = []
        for item in frame.name:
            if re.search('|'.join(boys), item) is not None:
                results = re.search('|'.join(boys), item)
                result.append(results)
    
        return result
    

    其中男孩是名字列表。

    【讨论】:

    • 我在这里运行你的代码,起初它没有返回任何东西。但后来我在 re.search cmd 上放了 re.IGNORECASE 标志,它返回了一个带有 [son, boy] 的列表(来自威廉哈里森的儿子和来自 Superboy 的男孩)。你能再解释一下你想在这里完成什么吗?
    猜你喜欢
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 2021-08-02
    • 2018-10-11
    • 2014-01-09
    • 1970-01-01
    相关资源
    最近更新 更多