首页 > 解决方案 > Python - 拆分 DataFrame 以制作训练集

问题描述

我有一个看起来像这样的 DataFrame,称为“sales_csv”:

    id     TV  radio  newspaper  sales  invested_amount  successful_campaign
0    1  230.1   37.8       69.2   22.1        15.253394                False
1    2   44.5   39.3       45.1   10.4        12.394231                False
2    3   17.2   45.9       69.3    9.3        14.236559                False
3    4  151.5   41.3       58.5   18.5        13.583784                False
4    5  180.8   10.8       58.4   12.9        19.379845                False

我试图将它拆分为一个训练集,但是当我运行它时它给了我这个错误:

ValueError: Found input variables with inconsistent numbers of samples: [80, 78]

这是我已经拥有的代码:

# Split.
X = sales_csv.iloc[0 : 80]
y = sales_csv.iloc[81 : 159]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 5)

# Training.
gauss = GaussianNB()

gauss.fit(X_train, y_train)

y_expect = y_test
y_pred = gauss.predict(X_test)

print(accuracy_score(y_expect, y_pred))

我正在使用 0 到 160 之间的行,但 DataFrame 有 +200 行。

标签: pythonpandasdataframetraining-data

解决方案


X 是除销售以外的所有列。并且 y = df['sales'].copy()

只有这样你才能用 train_split 拆分 X 和 y

但在此之前,您需要标记您的successful_campaign 列 - SKLEARN 库有很多上述示例。


推荐阅读