我有一个pandas数据框,df,如下所示:
column1
0 apple is a fruit
1 fruit sucks
2 apple tasty fruit
3 fruits what else
4 yup apple map
5 fire in the hole
6 that is true
我想生成一个column2,它是行中每个单词的列表以及整个列中每个单词的总数。所以输出应该是这样的。。。。在
^{pr2}$我尝试使用sklearn,但未能达到上述目的。需要帮助。在
from sklearn.feature_extraction.text import CountVectorizer
v = CountVectorizer()
x = v.fit_transform(df['text'])
以下是一种给出您想要的结果的方法,尽管它完全避免了
sklearn
:我不知道您是否可以使用}。在
scikit-learn
来实现这一点,但是您可以编写一个函数,然后使用apply()
将其应用于您的DataFrame
或{以下是您可以如何进行的示例:
如您所见,主要问题是
test.A.str.count(word)
将计算word
的所有出现次数,无论分配给word
的模式在字符串内。这就是为什么"a"
显示为发生4次。这应该很容易用一些正则表达式来解决(我不太擅长)。在或者,如果您愿意丢失一些单词,可以在上面的函数中使用此解决方法:
^{pr2}$相关问题 更多 >
编程相关推荐