【问题标题】:How do I extract a word from a pandas dataframe/series using a list in Python? [duplicate]如何使用 Python 中的列表从熊猫数据框/系列中提取单词? [复制]
【发布时间】:2020-08-21 18:03:33
【问题描述】:

我目前正在使用 str.contain 从系列中提取所需的单词。后来决定使用数据框来执行相同的操作。

text = pd.Series(['ENTER YOUR PIN NUMBER', 'ORDER READY FOR SHIPPING'])
text.str.contains('PIN', regex=False)

由于 SHIPPING 中也有一个 PIN,所以我得到的输出是,

True
True
dtype: bool

预期输出,

True
False
dtype: bool

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    如果你想知道句子中是否有一个确切的单词,你应该检查单词前后是否有空格。

    def check_word(sentence, word):
        return (' ' + word + ' ') in (' ' + sentence + ' ')
    
    list_validate=[]
    for sentences in text:
      list_validate.append(check_word(sentences, 'PIN'))
    

    返回:

    [True, False]
    

    为了将其概括为要检查的单词列表,不仅可以使用一个,您可以使用

    def check_word2(sentence,words):
      return any(' ' + word + ' ' in ' '+ sentence+' ' for word in words)
    
    

    【讨论】:

    • 这行得通。感谢您的回复。我如何在关键字列表上执行,例如 ls = ['PIN','SHOP','ORDER']。基本上它应该为所有这些关键字返回 TRUE。
    猜你喜欢
    • 1970-01-01
    • 2019-04-07
    • 2020-11-25
    • 1970-01-01
    • 2019-09-29
    • 2018-03-11
    • 2021-11-11
    • 2021-10-22
    • 2021-01-02
    相关资源
    最近更新 更多