Python 当一行包含另一行的字符串时,如何匹配行?
我的目标是找到与列Python 当一行包含另一行的字符串时,如何匹配行?,python,pandas,dataframe,row,contains,Python,Pandas,Dataframe,Row,Contains,我的目标是找到与列general\u text中的行匹配的City,但匹配必须精确 我试图在中使用搜索,但它没有给我预期的结果,因此我尝试使用str.contain,但我尝试这样做的方式显示了一个错误。关于如何正确或高效地完成这项工作,有什么提示吗 我尝试了基于 但它给我的结果如下: data = [['palm springs john smith':'spring'], ['palm springs john smith':'palm springs'], ['palm sp
general\u text
中的行匹配的City
,但匹配必须精确
我试图在中使用搜索,但它没有给我预期的结果,因此我尝试使用str.contain
,但我尝试这样做的方式显示了一个错误。关于如何正确或高效地完成这项工作,有什么提示吗
我尝试了基于
但它给我的结果如下:
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']]
您可以使用单词边界\b\b
进行精确匹配:
import re
f = lambda x: bool(re.search(r'\b{}\b'.format(x['City']), x['general_text']))
或:
这两种方法都工作得非常好,并且给出了相同的结果,但是re.search
和re.findall
之间有什么区别?@KWar-您可以检查-这里的工作原理是一样的,因为如果对re.search
使用bool,则使用None
,如果使用bool,则使用空列表[]
对于re.findall
也得到False
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