Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当一行包含另一行的字符串时,如何匹配行?_Python_Pandas_Dataframe_Row_Contains - Fatal编程技术网

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