将熊猫列添加到稀疏矩阵

邦森:

我想在模型中使用X变量的其他派生值。

XAll = pd_data[['title','wordcount','sumscores','length']]
y = pd_data['sentiment']
X_train, X_test, y_train, y_test = train_test_split(XAll, y, random_state=1)

当我使用标题中的文本数据时,我首先将其分别转换为dtm:

vect = CountVectorizer(max_df=0.5)
vect.fit(X_train['title'])
X_train_dtm = vect.transform(X_train['title'])
column_index = X_train_dtm.indices

print(type(X_train_dtm))    # This is <class 'scipy.sparse.csr.csr_matrix'>
print("X_train_dtm shape",X_train_dtm.get_shape())  # This is (856, 2016)
print("column index:",column_index)     # This is column index: [ 533  754  859 ...,  633  950 1339]

现在,我已经将文本作为文档术语矩阵,我想在X_train_dtm中添加数字等其他功能,例如'wordcount','sumscores','length'。这样,我将使用新的dtm创建模型,因此由于插入了附加功能,因此将更加准确。

如何将大熊猫数据框的其他数字列添加到稀疏的CSR矩阵中?

邦森:

找到了解决方案。我们可以使用sparse.hstack做到这一点:

from scipy.sparse import hstack
X_train_dtm = hstack((X_train_dtm,np.array(X_train['wordcount'])[:,None]))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章