如何使用Python中的列表从熊猫数据框/系列中提取单词?

时间:2020-05-06 17:01:53

标签: python pandas

我目前正在使用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

1 个答案:

答案 0 :(得分:0)

如果要确定句子中是否有确切单词,则应检查单词前后是否有空格。

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)