How to match rows when one row contain string from another row?

自古美人都是妖i 提交于 2019-12-24 07:35:56

问题


My aim is to find City that matches row from column general_text, but the match must be exact.

I was trying to use searching IN but it doesn't give me expected results, so I've tried to use str.contain but the way I try to do it shows me an error. Any hints on how to do it properly or efficient?

I have tried code based on 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)

but it gives me the result below:

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)

What I would like to receive by the code above is match only this:

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

回答1:


You can use word boundaries \b\b for exact match:

import re

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

Or:

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


来源:https://stackoverflow.com/questions/57950732/how-to-match-rows-when-one-row-contain-string-from-another-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!