Python将数据拆分为随机集

时间:2017-05-29 15:42:34

标签: python

我想将数据拆分为两个随机集。我做了第一部分:

ind = np.random.choice(df.shape[0], size=[int(df.shape[0]*0.7)], replace=False)
X_train = df.iloc[ind]

现在我想选择不在ind中的所有索引来创建我的测试集。请告诉我怎么做?

我以为会是

X_test = df.iloc[-ind]

但显然不是

3 个答案:

答案 0 :(得分:4)

结帐scikit-learn test_train_split()

文档示例:

>>> import numpy as np
>>> from sklearn.model_selection import train_test_split
>>> X, y = np.arange(10).reshape((5, 2)), range(5)
>>> X
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])
>>> list(y)
[0, 1, 2, 3, 4]

>>>

>>> X_train, X_test, y_train, y_test = train_test_split(
...     X, y, test_size=0.33, random_state=42)
...
>>> X_train
array([[4, 5],
       [0, 1],
       [6, 7]])
>>> y_train
[2, 0, 3]
>>> X_test
array([[2, 3],
       [8, 9]])
>>> y_test
[1, 4]

在你的情况下,你可以这样做:

larger, smaller = test_train_split(df, test_size=0.3)

答案 1 :(得分:1)

另一种获得70-30次列车测试分割的方法是生成指数,将它们混合然后分成70-30个部分。

ind = np.arange(df.shape[0])
np.random.shuffle(ind)
X_train = df.iloc[ind[:int(0.7*df.shape[0])],:]
X_test = df.iloc[ind[int(0.7*df.shape[0]):],:]

我建议将pandas.dataframe转换为数字矩阵并使用scikit-learn的train_test_split进行拆分,除非你真的想这样做。

答案 2 :(得分:0)

尝试这种纯Python方法。

ind_inversed = list(set(range(df.shape[0])) - set(ind))
X_test = df.iloc[ind_inversed]