PANDAS 从列中找到给定的 string/word
PANDAS find exact given string/word from a column
所以,我有一个 pandas 列名称 Notes,其中包含对某个事件的句子或解释。我正在尝试从该列中找到一些给定的词,当我找到该词时,我将其添加到下一列中作为 Type
问题出在某些特定的单词上,例如 Liar,Lies 其拾取单词 familiar和家庭因为他们都有骗子和谎言。
Notes Type
2 families are living in the address Lies
He is a liar Liar
We are not familiar with this Liar
从上面可以看出只有第二句是正确的。我怎么只选择单独的词,比如骗子、谎言,而不是家庭或熟悉的词。
这是我的方法,
word= ["Lies"]
for i in range(0, len(df)):
for f in word:
if f in df["Notes"][i]:
df["Type"][i] = "Lies"
感谢任何帮助。谢谢
在 regex
中使用 \b
作为单词边界,并使用 .str.extract
查找模式:
df.Notes.str.extract(r'\b(lies|liar)\b')
要标记包含该词的那些行,请执行:
df['Type'] = np.where(df.Notes.str.contains(r'\b(lies|liar)\b'), 'Lies', 'Not Lies')
好吧,我同意 Quang Hoang 的回答。请确保您了解 "He is not a liar" 这样的句子。它仍然匹配并给你骗子的地方。
我认为这篇代码适合你!
import pandas as pd
df = pd.DataFrame.from_dict({"Notes":["2 families are living in the address" ,
"He is a liar " ,
"We are not familiar with this " ] })
word= ["liar","are","this"]
found_in_whole_string =[]
for i in range(0, len(df)):
found_one_word=[]
for f in word:
if f in df["Notes"][i].split(" "):
found_one_word.append(f)
else:
found_one_word.append("")
found_in_whole_string.append(",".join([word for word in found_one_word if len(word) > 0]) )
df["type"] = found_in_whole_string
所以,我有一个 pandas 列名称 Notes,其中包含对某个事件的句子或解释。我正在尝试从该列中找到一些给定的词,当我找到该词时,我将其添加到下一列中作为 Type
问题出在某些特定的单词上,例如 Liar,Lies 其拾取单词 familiar和家庭因为他们都有骗子和谎言。
Notes Type
2 families are living in the address Lies
He is a liar Liar
We are not familiar with this Liar
从上面可以看出只有第二句是正确的。我怎么只选择单独的词,比如骗子、谎言,而不是家庭或熟悉的词。
这是我的方法,
word= ["Lies"]
for i in range(0, len(df)):
for f in word:
if f in df["Notes"][i]:
df["Type"][i] = "Lies"
感谢任何帮助。谢谢
在 regex
中使用 \b
作为单词边界,并使用 .str.extract
查找模式:
df.Notes.str.extract(r'\b(lies|liar)\b')
要标记包含该词的那些行,请执行:
df['Type'] = np.where(df.Notes.str.contains(r'\b(lies|liar)\b'), 'Lies', 'Not Lies')
好吧,我同意 Quang Hoang 的回答。请确保您了解 "He is not a liar" 这样的句子。它仍然匹配并给你骗子的地方。
我认为这篇代码适合你!
import pandas as pd
df = pd.DataFrame.from_dict({"Notes":["2 families are living in the address" ,
"He is a liar " ,
"We are not familiar with this " ] })
word= ["liar","are","this"]
found_in_whole_string =[]
for i in range(0, len(df)):
found_one_word=[]
for f in word:
if f in df["Notes"][i].split(" "):
found_one_word.append(f)
else:
found_one_word.append("")
found_in_whole_string.append(",".join([word for word in found_one_word if len(word) > 0]) )
df["type"] = found_in_whole_string