python - 如何将numpy数组附加到pandas数据帧

DBE*_*BE7 8 python numpy machine-learning pandas scikit-learn

我已经训练了一个Logistic回归分类器来预测评论是正面还是负面.现在,我想将函数返回的预测概率附加predict_proba到包含评论的Pandas数据框中.我尝试过这样的事情:

test_data['prediction'] = sentiment_model.predict_proba(test_matrix)
Run Code Online (Sandbox Code Playgroud)

显然,这不起作用,因为predict_proba返回2D-numpy数组.那么,最有效的方法是什么?我test_matrix用SciKit-Learn的CountVectorizer 创建:

vectorizer = CountVectorizer(token_pattern=r'\b\w+\b')
train_matrix = vectorizer.fit_transform(train_data['review_clean'].values.astype('U'))
test_matrix = vectorizer.transform(test_data['review_clean'].values.astype('U'))
Run Code Online (Sandbox Code Playgroud)

示例数据如下所示:

| Review                                     | Prediction         |                      
| ------------------------------------------ | ------------------ |
| "Toy was great! Our six-year old loved it!"|   0.986            |
Run Code Online (Sandbox Code Playgroud)

Kar*_*ham 14

将预测分配给变量,然后从变量中提取要分配给pandas dataframe cols的列.如果x是具有预测的2D numpy数组,

x = sentiment_model.predict_proba(test_matrix)
Run Code Online (Sandbox Code Playgroud)

那你可以做到,

test_data['prediction0'] = x[:,0]
test_data['prediction1'] = x[:,1]
Run Code Online (Sandbox Code Playgroud)