问题
So, I have a pandas column name Notes which contains a sentence or explanation of some event. I am trying find some given words from that column and when I find that word I am adding that to the next column as Type
The problem is for some specific word for example Liar, Lies its picking up word like familiar and families because they both have liar and lies in them.
Notes Type
2 families are living in the address Lies
He is a liar Liar
We are not familiar with this Liar
As you can see from above only the second sentence is correct. How do I only pick up separate word like liar, lies and not families or familiar.
This was my approach,
word= ["Lies"]
for i in range(0, len(df)):
for f in word:
if f in df["Notes"][i]:
df["Type"][i] = "Lies"
Appreciate any help. Thanks
回答1:
Use \b
for word boundary in regex
, and .str.extract
to find pattern:
df.Notes.str.extract(r'\b(lies|liar)\b')
To label those rows containing that word, do:
df['Type'] = np.where(df.Notes.str.contains(r'\b(lies|liar)\b'), 'Lies', 'Not Lies')
回答2:
Well I agree with Quang Hoang answer. Please make sure you are aware about sentences like "He is not a liar". Where it will still match and give you Liar.
回答3:
I think this piece if code will work fine for you!
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
来源:https://stackoverflow.com/questions/62432059/pandas-find-exact-given-string-word-from-a-column