【问题标题】:How to match rows when one row contain string from another row?当一行包含另一行的字符串时如何匹配行?
【发布时间】:2020-01-16 22:19:01
【问题描述】:

我的目标是找到与general_text 列中的行匹配的City,但匹配必须准确。

我尝试使用搜索IN,但它没有给我预期的结果,所以我尝试使用str.contain,但我尝试这样做的方式向我显示了一个错误。有关如何正确或高效地执行此操作的任何提示?

我已经尝试过基于Filtering out rows that have a string field contained in one of the rows of another column of strings的代码

df['matched'] = df.apply(lambda x: x.City in x.general_text, axis=1)

但它给了我以下结果:

data = [['palm springs john smith':'spring'],
    ['palm springs john smith':'palm springs'],
    ['palm springs john smith':'smith'],
    ['hamptons amagansett':'amagansett'],
    ['hamptons amagansett':'hampton'],
    ['hamptons amagansett':'gans'],
    ['edward riverwoods lake':'wood'],
    ['edward riverwoods lake':'riverwoods']]

df = pd.DataFrame(data, columns = [ 'general_text':'City'])

df['match'] = df.apply(lambda x: x['general_text'].str.contain(
                                          x.['City']), axis = 1)

我想通过上面的代码收到的是只匹配这个:

data = [['palm springs john smith':'palm springs'],
    ['hamptons amagansett':'amagansett'],
    ['edward riverwoods lake':'riverwoods']]

【问题讨论】:

    标签: python pandas dataframe row contains


    【解决方案1】:

    您可以使用字边界\b\b 进行精确匹配:

    import re
    
    f = lambda x: bool(re.search(r'\b{}\b'.format(x['City']), x['general_text']))
    

    或者:

    f = lambda x: bool(re.findall(r'\b{}\b'.format(x['City']), x['general_text']))
    
    df['match'] = df.apply(f, axis = 1)
    print (df)
                  general_text          City  match
    0  palm springs john smith        spring  False
    1  palm springs john smith  palm springs   True
    2  palm springs john smith         smith   True
    3      hamptons amagansett    amagansett   True
    4      hamptons amagansett       hampton  False
    5      hamptons amagansett          gans  False
    6   edward riverwoods lake          wood  False
    7   edward riverwoods lake    riverwoods   True
    

    【讨论】:

    • 两者都可以正常工作并给出相同的结果,但re.searchre.findall 之间有什么区别?
    • @KWar - 你可以检查this - 这里的工作方式相同,因为如果使用带有None 的布尔值re.search 得到False 并且如果使用带有空列表的布尔值[] re.findall 也得到 False
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多