【问题标题】:Get count vectorizer vocabulary in new dataframe column by applying vectorizer on existing dataframe column using pandas通过使用 pandas 在现有数据框列上应用矢量化器来获取新数据框列中的计数矢量化器词汇
【发布时间】:2020-11-08 22:15:30
【问题描述】:

我有一个数据框列“review”,其中包含“Food was Awesome”之类的内容,我想要一个新列来计算每个单词的重复次数。

name      The First Years Massaging Action Teether
review                    A favorite in our house!
rating                                           5
Name: 269, dtype: object

期望像 ['Food':1,'was':1,'Awesome':1] 这样的输出 我尝试使用 for 循环,但执行时间太长

for row in range(products.shape[0]):
try:        
    count_vect.fit_transform([products['review_without_punctuation'][row]])
    products['word_count'][row]=count_vect.vocabulary_
except:
    print(row)

我想不使用 for 循环。

【问题讨论】:

  • 为什么fit 每一行而transform 单独一行?
  • 我只是试了一下..我想不为每一行做

标签: pandas scikit-learn countvectorizer


【解决方案1】:

我找到了解决方案。 我已经定义了这样的函数-

def Vectorize(text):
try:
    count_vect.fit_transform([text])
    return count_vect.vocabulary_
except:
    return-1

并应用上述功能-

from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
products['word_count'] = products['review_without_punctuation'].apply(Vectorize)

这个解决方案奏效了,我在新专栏中获得了词汇。

【讨论】:

    【解决方案2】:

    您可以像这样获取所有文档的计数向量:

    cv = CountVectorizer()
    count_vectors = cv.fit_transform(products['review_without_punctuation'])
    

    要通过索引获取特定文档的数组格式的计数向量,例如第一个文档,

    count_vectors[0].toarray()
    

    词汇在

    cv.vocabulary_
    

    要获得构成计数向量的单词,例如,对于第一个文档,请使用

    cv.inverse_transform(count_vectors[0])
    

    【讨论】:

    • 感谢您的回复。我找到了解决方案并发布了答案。
    猜你喜欢
    • 2021-03-03
    • 2019-10-02
    • 2018-02-05
    • 1970-01-01
    • 2021-10-11
    • 2016-12-22
    • 2023-03-12
    • 2012-12-03
    • 2018-07-28
    相关资源
    最近更新 更多