我有一列包含每个文本中的第一个单词,并试图检查它是否在nltk单词列表中。我的代码是:
from nltk.corpus import words
wordlist = words.words()
reviews['test'] = reviews.apply(lambda x: True if x['FIRST_WORD'] in wordlist else False )我收到一个错误:
KeyError: 'FIRST_WORD'不知道为什么,因为这肯定是我的数据集中的列的名称。我把lambda函数设置错了吗?
发布于 2021-03-22 22:23:35
语法不正确。正确的语法是:
>>> df
FIRST_WORD SECOND_WORD
0 hello blah
1 hi blah
2 xyz blah
>>> df.apply(lambda x: True if x['FIRST_WORD'] in wordlist else False, axis=1)
0 True
1 True
2 False
dtype: bool
>>> # OR
>>> df['FIRST_WORD'].apply(lambda x : True if x in wordlist else False)
0 True
1 True
2 False
Name: FIRST_WORD, dtype: bool说,
您可能希望检查单个列上的操作的isin.和apply与map之间的差异。
>>> df['FIRST_WORD'].isin(wordlist)
0 True
1 True
2 False
Name: FIRST_WORD, dtype: boolhttps://stackoverflow.com/questions/66754259
复制相似问题