在Python中将CountVectorizer应用于具有行中单词列表的列 [英] Apply CountVectorizer to column with list of words in rows in Python

查看:18
本文介绍了在Python中将CountVectorizer应用于具有行中单词列表的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个文本分析的预处理部分,在删除停用词和词干后:

test[col] = test[col].apply(
    lambda x: [ps.stem(item) for item in re.findall(r"[w']+", x) if ps.stem(item) not in stop_words])

train[col] = train[col].apply(
    lambda x: [ps.stem(item) for item in re.findall(r"[w']+", x) if ps.stem(item) not in stop_words])

我有一个专栏,里面有"干净的单词"的列表。以下是一列中的3行:

['size']
['pcs', 'new', 'x', 'kraft', 'bubble', 'mailers', 'lined', 'bubble', 'wrap', 'protection', 'self', 'sealing', 'peelandseal', 'adhesive', 'keeps', 'contents', 'secure', 'tamper', 'proof', 'durable', 'lightweight', 'kraft', 'material', 'helps', 'save', 'postage', 'approved', 'ups', 'fedex', 'usps']
['brand', 'new', 'coach', 'bag', 'bought', 'rm', 'coach', 'outlet']

我现在要将CountVectorizer应用于此列

from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features=1500, analyzer='word', lowercase=False) # will leave only 1500 words
X_train = cv.fit_transform(train[col])

但我收到一个错误:

TypeError: expected string or bytes-like object

从列表中创建字符串,然后再用CountVectorizer分隔,这会有点奇怪。

推荐答案

因为我找不到避免错误的其他方法,所以我加入了列

中的列表
train[col]=train[col].apply(lambda x: " ".join(x) )
test[col]=test[col].apply(lambda x: " ".join(x) )

之后我才开始得到结果

X_train = cv.fit_transform(train[col])
X_train=pd.DataFrame(X_train.toarray(), columns=cv.get_feature_names())

这篇关于在Python中将CountVectorizer应用于具有行中单词列表的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆