Python 将数据文件洗牌并拆分为训练集和测试集
我正在尝试使用pandas和numpy将数据文件洗牌并拆分为训练集和测试集,因此我执行了以下操作:Python 将数据文件洗牌并拆分为训练集和测试集,python,numpy,pandas,Python,Numpy,Pandas,我正在尝试使用pandas和numpy将数据文件洗牌并拆分为训练集和测试集,因此我执行了以下操作: import pandas as pd import numpy as np data_path = "/path_to_data_file/" train = pd.read_csv(data_path+"product.txt", header=0, delimiter="|") ts = train.shape #print "data dimension", ts #print
import pandas as pd
import numpy as np
data_path = "/path_to_data_file/"
train = pd.read_csv(data_path+"product.txt", header=0, delimiter="|")
ts = train.shape
#print "data dimension", ts
#print "product attributes \n", train.columns.values
#shuffle data set, and split to train and test set.
df = pd.DataFrame(train)
new_train = df.reindex(np.random.permutation(df.index))
indice_90_percent = int((ts[0]/100.0)* 90)
print "90% indice", indice_90_percent
#write train products to csv
#new_train.to_csv(sep="|")
with open('train_products.txt', 'w') as f:
for i in new_train[:indice_90_percent]:
f.write(i+'\n')
with open('test_products.txt', 'w') as f:
for i in new_train[indice_90_percent:]:
f.write(i+'\n')
但是,我没有得到包含数据行的训练和测试文件,而是得到两个包含列名称的文件。我遗漏了什么?如果不希望列名使用header=False
,可以使用来写入行
new_train[indice_90_percent:].to_csv('test_products.txt',header=False)
new_train[:indice_90_percent].to_csv('train_products.txt',header=False)
您正在迭代列名,行位于
new_train[indice_90_percent:]中。值
这是因为从df返回的iterable是列,而不是rows@EdChum我想对这些行进行迭代,如何继续?很抱歉,您想将每一行或整个df写入文件,索引为indice\u 90%
?@MedAli,您可以使用pandali将new\u train[indice\u 90\u%::]写入csv('test\u products.txt',header=False)