2016-07-25 105 views
0

我想将一个pandas DataFrame划分为十个不相交,大小相同,随机组成的子集。Python/Pandas - 将10个不相交,相同大小的子集划分为一个pandas DataFrame

我知道我可以随机抽取使用原始数据框大熊猫的十分之一:

partition_1 = pandas.DataFrame.sample(frac=(1/10)) 

但是,我怎么能得到其他九个分区?如果我再次执行pandas.DataFrame.sample(frac=(1/10)),则存在我的子集不相交的可能性。

感谢您的帮助!

+0

这已经得到了解答:刚结合[这](http://stackoverflow.com/a/17315875/2077270)与[这里](http://stackoverflow.com/a/15772356/2077270 ) – dermen

回答

0

使用np.random.permutations

df.loc[np.random.permutation(df.index)]

将洗牌数据帧,并保持列名,之后您可以将数据帧分成10

0

df是你的数据帧,并且要N_PARTITIONS分区大小相同(如果​​可以被N_PARTITIONS整除,它们将是,正好是等号)。

使用np.random.permutation来排列阵列np.arange(len(df))。然后用步骤N_PARTITIONS对该数组进行切片,并使用.iloc[]提取数据帧的对应行。

import numpy as np 

permuted_indices = np.random.permutation(len(df)) 

dfs = [] 
for i in range(N_PARTITIONS): 
    dfs.append(df.iloc[permuted_indices[i::N_PARTITIONS]]) 

既然你是在Python 2.7版,它可能是更好地xrange(N_PARTITIONS)切换range(N_PARTITIONS)得到一个迭代器,而不是一个列表。

0

从此开始。

dfm = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo']*2, 
         'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three']*2}) 

    A  B 
0 foo one 
1 bar one 
2 foo two 
3 bar three 
4 foo two 
5 bar two 
6 foo one 
7 foo three 
8 foo one 
9 bar one 
10 foo two 
11 bar three 
12 foo two 
13 bar two 
14 foo one 
15 foo three 

Usage: 
Change "4" to "10", use [i] to get the slices. 

np.random.seed(32) # for reproducible results. 
np.array_split(dfm.reindex(np.random.permutation(dfm.index)),4)[1] 
     A B 
2 foo two 
5 bar two 
10 foo two 
12 foo two 

np.array_split(dfm.reindex(np.random.permutation(dfm.index)),4)[3] 

    A  B 
13 foo two 
11 bar three 
0 foo one 
7 foo three 
+0

如果答案有效,请考虑接受它,你也可以upvote。 – Merlin

相关问题