拆分数据框以测试和训练数据集

Splitting data frame in to test and train data sets

Use pandas to create two data frames: train_df and test_df, where train_df has 80% of the data chosen uniformly at random without replacement.

这里,“无放回地随机统一选择的数据”是什么意思?

还有,我该怎么做?

谢谢

"chosen uniformly at random"表示每一行被选入80%的概率相等

"without replacement"表示每一行只考虑一次。一旦它被分配到训练或测试集,它就不是

例如,考虑以下数据:

A            B

0            5
1            6
2            7
3            8
4            9

如果将此数据集拆分为 80% 的训练集和 20% 的测试集,那么我们最终将得到 4 行的训练集(80% 的数据)和 1 行的测试集( 20%的数据)

无替换 假设第一行分配给训练集。现在训练集是:

A            B

0            5

当下一行分配给训练或测试时,它将从剩余的行中选择: B

1            6
2            7
3            8
4            9

有替换 假设第一行分配给训练集。现在训练集是:

A            B

0            5

但下一行将使用整个数据集分配(即第一行已放回原始数据集中)

A            B

0            5
1            6
2            7
3            8
4            9

你怎么做到的: 您可以使用 scikit-learn 中的 train_test_split 函数:http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html

或者您可以使用 pandas 和 Numpy 来做到这一点:

df['random_number'] = np.random.randn(length_of_df)

train = df[df['random_number'] <= 0.8]
test = df[df['random_number'] > 0.8]