我试图用Pandas读取一个相当大的CSV文件,并将其分成两个随机块,其中一个是10%的数据,另一个是90%的数据。
这是我目前的尝试:
rows = data.index
row_count = len(rows)
random.shuffle(list(rows))
data.reindex(rows)
training_data = data[row_count // 10:]
testing_data = data[:row_count // 10]
由于某些原因,当我尝试在支持向量机分类器中使用这些生成的DataFrame对象之一时,sklearn
抛出此错误:
IndexError: each subindex must be either a slice, an integer, Ellipsis, or newaxis
我想我做错了。有没有更好的方法来做这件事?
发布于 2012-08-30 15:36:19
你用的是什么版本的熊猫?对我来说,你的代码运行得很好(我在git master上)。
另一种方法可以是:
In [117]: import pandas
In [118]: import random
In [119]: df = pandas.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
In [120]: rows = random.sample(df.index, 10)
In [121]: df_10 = df.ix[rows]
In [122]: df_90 = df.drop(rows)
较新的版本(从0.16.1开始)直接支持这一点:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html
发布于 2013-06-18 22:41:40
我发现NumPy 1.7.0中的np.random.choice()
新特性在这方面工作得很好。
例如,您可以传递来自DataFrame的索引值和整数10,以选择10个随机均匀采样的行。
rows = np.random.choice(df.index.values, 10)
sampled_df = df.ix[rows]
发布于 2015-11-18 06:53:29
版本0.16.1中的新功能:
sample_dataframe = your_dataframe.sample(n=how_many_rows_you_want)
这里的文档:http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.sample.html
https://stackoverflow.com/questions/12190874
复制相似问题