Ble*_*der 68 python partitioning pandas
我正在尝试用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]
Run Code Online (Sandbox Code Playgroud)
出于某种原因,sklearn当我尝试在SVM分类器中使用这些结果DataFrame对象之一时抛出此错误:
IndexError: each subindex must be either a slice, an integer, Ellipsis, or newaxis
Run Code Online (Sandbox Code Playgroud)
我想我做错了.有一个更好的方法吗?
Wou*_*ire 80
您使用的是哪个版本的熊猫?对我来说,你的代码工作正常(我在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)
Run Code Online (Sandbox Code Playgroud)
较新的版本(从0.16.1开始)直接支持这个:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html
dra*_*jub 79
我发现np.random.choice()NumPy 1.7.0 中的新功能对此非常有效.
例如,您可以从DataFrame传递索引值,并使用整数10来选择10个随机均匀采样的行.
rows = np.random.choice(df.index.values, 10)
sampled_df = df.ix[rows]
Run Code Online (Sandbox Code Playgroud)
dva*_*val 24
版本0.16.1中的新增内容:
sample_dataframe = your_dataframe.sample(n=how_many_rows_you_want)
Run Code Online (Sandbox Code Playgroud)
doc here:http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.sample.html
如果您正在使用pandas.read_csv,则可以使用skiprows参数在加载数据时直接进行采样.这是我写的一篇简短的文章 - https://nikolaygrozev.wordpress.com/2015/06/16/fast-and-simple-sampling-in-pandas-when-loading-data-from-files/