[英]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%。 当我想将此数据集分为训练/测试集时,我想均等/均匀地分布数据集中的1个预测。
在改组期间我该怎么做?
除了重新发明轮子之外 ,您还可以结合使用Pandas和Scikit-Learn 。 特别是,您可以在Pandas Dataframe中读取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)
在此处查看有关train_test_split
更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.