我想通过在另一列中的单词列表上运行单词词干功能来创建一个新的pandas列。我可以使用apply和lambda来标记单个字符串,但我无法弄清楚如何将其推断为在单词列表上运行它。
test = {'Statement' : ['congratulations on the future','call the mechanic','more text'], 'Other' : [2,3,4]}
df = pd.DataFrame(test)
df['tokenized'] = df.apply (lambda row: nltk.word_tokenize(row['Statement']), axis=1)
我知道我可以用嵌套的for循环来解决它,但这似乎效率低下并导致一个SettingWithCopyWarning:
df['stems'] = ''
for x in range(len(df)):
print(len(df['tokenized'][x]))
df['stems'][x] = row_stems=[]
for y in range(len(df['tokenized'][x])):
print(df['tokenized'][x][y])
row_stems.append(stemmer.stem(df['tokenized'][x][y]))
有没有更好的方法来做到这一点?
编辑:
以下是结果应如下所示的示例:
Other Statement tokenized stems
0 2 congratulations on the future [congratulations, on, the, future] [congratul, on, the, futur]
1 3 call the mechanic [call, the, mechanic] [call, the, mechan]
2 4 more text [more, text] [more, text]
答案 0 :(得分:1)
确实不需要运行循环。至少不是一个明确的循环。列表理解将正常工作。
假设您使用Porter词干ps
:
df['stems'] = df['tokenized'].apply(lambda words:
[ps.stem(word) for word in words])