【问题标题】:PANDAS find exact given string/word from a columnPANDAS 从列中找到确切的给定字符串/单词
【发布时间】:2020-10-07 10:51:49
【问题描述】:

所以,我有一个 pandas 列名称 Notes,其中包含对某些事件的句子或解释。我正在尝试从该列中找到一些给定的单词,当我找到该单词时,我将其作为 Type

添加到下一列

问题出在某些特定的词上,例如 LiarLiesfamiliarfamilies 这样的词> 因为他们都有说谎者,并且在他们身上撒谎。

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"

感谢任何帮助。谢谢

【问题讨论】:

标签: python pandas text-mining


【解决方案1】:

使用\b 作为regex 中的单词边界,使用.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')

【讨论】:

  • 谢谢。那么如何根据行分配类型呢?
  • df['Type'] = df.Notes.str.extract(r'\b(lies|liar)\b')[0]?也许用.str.capitalize()链接它
  • 我想将这些词的类型指定为“谎言”。有什么办法吗?
  • 谢谢。该代码运行良好,但只是一个小问题。如果您再次为不同的单词分配不同的类型,它只会覆盖第一个。
【解决方案2】:

嗯,我同意 Quang Hoang 的回答。请确保您了解诸如“他不是骗子”之类的句子。它仍然会匹配并给你骗子。

【讨论】:

    【解决方案3】:

    我认为如果代码对你来说很好用!

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      相关资源
      最近更新 更多