【问题标题】:Pandas - Extract common substring between 2 columnsPandas - 提取两列之间的公共子字符串
【发布时间】:2022-08-15 22:37:29
【问题描述】:

我有 2 个数据框,我们称它们为 A 和 B。我想要做的是在 DF A 中创建第二列,其中包含 2 个 DF 之间的公共子字符串。

后卫:一个

String
012IREze
SecondString
LastEntry

后卫:乙

String
IREPP
StringNumber2
LastEntry123

期望的输出

String Common String
012IREze IRE
SecondString String
LastEntry111 LastEntry

我在网上找到了下面的代码,但是在处理列时我无法让它工作

match = SequenceMatcher(None, string1, string2).find_longest_match(0, len(string1), 0, len(string2))

print(match)  # -> Match(a=0, b=15, size=9)
print(string1[match.a: match.a + match.size])  # -> apple pie
print(string2[match.b: match.b + match.size])  # -> apple pie

    标签: python


    【解决方案1】:

    IIUC,一种方法是将 zip 应用于两个数据框列并应用客户函数

    代码

    import pandas as pd
    from io import StringIO
    from difflib import SequenceMatcher
    
    def lcs(x, y):
        '''
            Custom function to find LCS between strings x, y
        '''
        match = SequenceMatcher(None, x, y).find_longest_match(0, len(x), 0, len(y))
        if match.size > 0:
            return x[match.a:match.a + match.size]
        else:
            return ""
        
    # Zip desired columns of two data frames and apply to a custom function
    # in a list comprehension
    dfa['LCS'] = [lcs(x, y) for x, y in zip(dfa['String'], dfb['String'])]
    

    示例用法

    sa = '''String
    012IREze
    SecondString
    LastEntry
    random'''
    
    sb = '''String
    IREPP
    StringNumber2
    LastEntry123
    blue'''
    
    dfa = pd.read_csv(StringIO(sa), sep = '\n')
    dfb = pd.read_csv(StringIO(sb), sep = '\n')
    
    # Zip desired columns of two dataframes and apply to custom function
    dfa['LCS'] = [lcs(x, y) for x, y in zip(dfa['String'], dfb['String'])]
    
    print(dfa)
    

    输出

        String        LCS
    0   012IREze      IRE
    1   SecondString  String
    2   LastEntry     LastEntry
    3   random  
    

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      相关资源
      最近更新 更多