按组随机播放 pandas 数据框

Shuffle a pandas dataframe by groups

我的数据框看起来像这样

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

我该怎么做?如果我的示例不清楚,请告诉我。

假设您想在 sampleID 之前洗牌。先df.groupby,洗牌(先import random),然后调用pd.concat:

import random

groups = [df for _, df in df.groupby('sampleID')]
random.shuffle(groups)

pd.concat(groups).reset_index(drop=True)

   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) 重置索引,但这是一个可选步骤。

只是向@cs95 的回答添加一件事。 如果你想按 sampleID 洗牌,但你想让你的 sampleIDs 从 1 开始排序。 所以这里 sampleID 不是那么重要. 这是一个解决方案,您只需迭代 gourped 数据帧并更改 sampleID.

groups = [df for _, df in df.groupby('doc_id')]

random.shuffle(groups)

for i, df in enumerate(groups):
     df['doc_id'] = i+1

shuffled = pd.concat(groups).reset_index(drop=True)

        doc_id  sent_id  word_id
   0       1        1       20
   1       1        2       94
   2       1        3       99
   3       2        1       63
   4       2        2       23
   5       2        3       73
   6       3        1       73
   7       3        2       56
   8       3        3       34

我发现这比接受的答案快得多:

ids = df["sampleID"].unique()
random.shuffle(ids)
df = df.set_index("sampleID").loc[ids].reset_index()

出于某种原因,pd.concat 是我用例中的瓶颈。无论如何,您都可以避免串联。