2017-08-09 133 views
0

我的數據框看起來像這樣按組洗牌大熊貓據幀

sampleID col1 col2 
    1  1 63 
    1  2 23 
    1  3 73 
    2  1 20 
    2  2 94 
    2  3 99 
    3  1 73 
    3  2 56 
    3  3 34 

我需要洗牌數據框保持相同的樣品一起和COL1的順序必須相同上述數據幀。

所以我需要像這樣

sampleID col1 col2 
    2  1 20 
    2  2 94 
    2  3 99 
    3  1 73 
    3  2 56 
    3  3 34 
    1  1 63 
    1  2 23 
    1  3 73 

我怎樣才能做到這一點?如果我的例子不清楚,請讓我知道。

回答

1

假設你想要洗牌sampleID。首先df.groupby,洗牌(import random第一),然後調用pd.concat

In [423]: groups = [df for _, df in df.groupby('sampleID')] 

In [424]: random.shuffle(groups) 

In [427]: pd.concat(groups).reset_index(drop=True) 
Out[427]: 
    sampleID col1 col2 
0   2  1 20 
1   2  2 94 
2   2  3 99 
3   1  1 63 
4   1  2 23 
5   1  3 73 
6   3  1 73 
7   3  2 56 
8   3  3 34 

您與df.reset_index(drop=True)重置索引,但它是一個可選的步驟。