簡體   English   中英

Pandas DataFrame-檢查A列中的字符串是否包含B列中的完整單詞字符串

[英]Pandas DataFrame - check if string in column A contains full word string in column B

我有一個包含兩列foo的數據bar ,其中foo包含文本字符串,而bar包含搜索項字符串。 對於數據框中的每一行,我要檢查搜索詞是否在帶有單詞邊界的文本字符串中。

例如

import pandas as pd
import numpy as np
import re

df = pd.DataFrame({'foo':["the dog is blue", "the cat isn't orange"], 'bar':['dog', 'cat is']})

df
      bar                   foo
0     dog       the dog is blue
1  cat is  the cat isn't orange

本質上,我想向量化以下操作

re.search(r"\bdog\b", "the dog is blue") is not None  # True
re.search(r"\bcat is\b", "the cat isn't orange") is not None  # False

考慮到我正在處理數十萬行,什么是快速的方法? 我嘗試使用str.contains方法,但無法完全理解

您可以將函數應用於每一行:

df.apply(lambda x: re.search(r'\b' + x.bar + r'\b', x.foo) is not None, axis=1)

結果:

0     True
1    False
dtype: bool
df.apply(lambda x: re.search(r'\b{0}\b'.format(x.bar), x.foo) is not None, axis='columns')

df.apply將通用函數應用於pandas行或列,請參見此處: http ://pandas.pydata.org/pandas-docs/stable/genic/pandas.DataFrame.apply.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM