按组随机排列 pandas 数据框 [英] Shuffle a pandas dataframe by groups

查看:65
本文介绍了按组随机排列 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框看起来像这样

My dataframe looks like this

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的顺序必须与上述数据帧中的顺序相同.

I need to shuffle the dataframe keeping same samples together and the order of the col1 must be same as in above dataframe.

所以我需要这样

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

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

How can I do this? If my example is not clear please let me know.

推荐答案

假设您要按sampleID进行洗牌.首先df.groupby,先洗牌(先import random),然后再调用pd.concat:

Assuming you want to shuffle by sampleID. First df.groupby, shuffle (import random first), and then call 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)重设索引,但这是可选步骤.

You reset the index with df.reset_index(drop=True), but it is an optional step.

这篇关于按组随机排列 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆