python 中的 csv 文件中的一种行随机排列并均匀分布

Shuffle and spread uniformly one kind of row in a csv file in python

我有一个数据集 csv 文件,其特征和预测如下所示:

Feature1    Feature2    Prediction
214         ast         0
222         bbr         0
845         iop         0
110         frn         1
...

我正在尝试以这种方式随机播放 csv 文件:

import csv
import random

with open("dataset.csv") as f:
    r = csv.reader(f)
    header, l = next(r), list(r)

random.shuffle(l)

with open("dataset_shuffled.csv", "wb") as f:
    csv.writer(f).writerows([header] + l)

然而,预测值为 1 的行仅占整个数据集的 1%。 因为我想将这个数据集分成 train/test 组,所以我想在数据集中传播 equally/uniformly 1 个预测。

我该如何在洗牌过程中做到这一点?

而不是重新发明轮子也许你可以使用Pandas and Scikit-Learn的组合。特别是您可以在 Pandas 数据框中读取 csv,例如:

import pandas
df = pandas.read_csv('your_csv.csv')

此时您可能想要创建 x(功能集)和 y(目标):

x = df[['Feature1', 'Feature2']]
y = df[['Prediction']]

并使用 Scikit-Learn 创建训练集和测试集:

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)

查看 here 了解有关 train_test_split 的更多详细信息。