Skip to main content
 首页 » 编程设计

python之将列添加到python中的数据集

2025年05月04日24me-sa

我正在尝试用 Python 将预测数据添加回我的原始数据集。我想我应该使用 Pandas、ASSIGN 和 pd.DataFrame,但在阅读所有文档后我不知道如何编写它(抱歉,我是新手,最近才开始学习编码)。我在下面编写了我的代码,只需要有关将我的预测添加回数据集的代码的帮助。感谢您的帮助!

# Importing the libraries 
import numpy as np 
import matplotlib.pyplot as plt 
import pandas as pd 
 
# Importing the dataset 
dataset = pd.read_csv('Social_Network_Ads.csv') 
X = dataset.iloc[:, [2, 3]].values 
y = dataset.iloc[:, 4].values 
 
# Splitting the dataset into the Training set and Test set 
from sklearn.cross_validation import train_test_split 
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25,      
random_state = 0) 
 
# Feature Scaling X_train and X_test 
from sklearn.preprocessing import StandardScaler 
sc = StandardScaler() 
X_train = sc.fit_transform(X_train) 
X_test = sc.transform(X_test) 
 
#Feature scaling the all independent variables used to build the model 
whole_dataset = sc.transform(X) 
 
# Fitting classifier to the Training set 
# Create your Naive Bayes here 
from sklearn.naive_bayes import GaussianNB 
classifier = GaussianNB() 
classifier.fit(X_train, y_train) 
 
# Predicting the Test set results 
y_pred = classifier.predict_proba(X_test) 
 
# Predicting the results for the whole dataset 
y_pred2 = classifier.predict_proba(whole_dataset)  
 
# Add y_pred2 predictions back to the dataset 
??? 

请您参考如下方法:

您只需执行 dataset['prediction'] = y_pred 即可添加新列。

Pandas 支持用于添加新列的简单语法,这里它将添加一个新列,并且可能会查看从 sklearn 返回的 numpy 数组,因此它应该既好又快。

编辑

查看您的代码和数据,您误解了 train_test_split 的作用,这是将数据拆分为原始数据集的 3/4 1/4 拆分,该数据集有 400 行,您的 X训练数据包含300行,测试数据为100行。然后,您将尝试分配回 400 行的原始数据集。首先,行数不匹配,其次,predict_proba 返回的是预测类百分比矩阵。因此,训练后您想做的是对原始数据集进行预测,并通过子选择每一列将其分配回 2 列:

y_pred = classifier.predict_proba(X) 

现在将其分配回去:

dataset['predict_class_1'],dataset['predict_class_2'] = y_pred[:,0],y_pred[:,1]