2016-07-25 104 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

相關問題