【发布时间】:2017-04-05 09:05:34
【问题描述】:
我正在尝试将 predict 方法的结果与 pandas.DataFrame 对象中的原始数据合并回来。
from sklearn.datasets import load_iris
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
import pandas as pd
import numpy as np
data = load_iris()
# bear with me for the next few steps... I'm trying to walk you through
# how my data object landscape looks... i.e. how I get from raw data
# to matrices with the actual data I have, not the iris dataset
# put feature matrix into columnar format in dataframe
df = pd.DataFrame(data = data.data)
# add outcome variable
df['class'] = data.target
X = np.matrix(df.loc[:, [0, 1, 2, 3]])
y = np.array(df['class'])
# finally, split into train-test
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8)
model = DecisionTreeClassifier()
model.fit(X_train, y_train)
# I've got my predictions now
y_hats = model.predict(X_test)
要将这些预测与原始 df 合并回来,我试试这个:
df['y_hats'] = y_hats
但这引发了:
ValueError:值的长度与索引的长度不匹配
我知道我可以将df 拆分为train_df 和test_df 并且这个问题将得到解决,但实际上我需要按照上面的路径创建矩阵X 和y(我的实际问题是一个文本分类问题,我在拆分成训练和测试之前对整个特征矩阵进行了归一化)。我如何将这些预测值与我的df 中的适当行对齐,因为y_hats 数组是零索引的,并且似乎所有关于哪些行的信息都包含在X_test 和@ 987654335@丢了?还是我会被降级为先将数据帧拆分为训练测试,然后再构建特征矩阵?我只想用数据框中的np.nan 值填充train 中包含的行。
【问题讨论】:
-
我相信
sklearn支持DataFrames和Series作为train_test_split的参数所以它应该通过传递你的df 的一个子部分来工作,除了返回的是索引所以您可以使用iloc使用这些索引回您的 df,请参阅文档:scikit-learn.org/stable/modules/generated/…
标签: python pandas scikit-learn