Skip to main content
 首页 » 编程设计

python之在 pandas 的 groupby 之后选择样本随机组

2025年05月04日14Terrylee

我有一个非常大的 DataFrame,看起来像这个例子 df:

df =  
 
col1    col2     col3  
apple   red      2.99  
apple   red      2.99  
apple   red      1.99  
apple   pink     1.99  
apple   pink     1.99  
apple   pink     2.99  
...     ....      ... 
pear    green     .99  
pear    green     .99  
pear    green    1.29 

我像这样按 2 列分组:

g = df.groupby(['col1', 'col2']) 

现在我想选择 3 个随机组。所以我的预期输出是这样的:

col1    col2     col3  
apple   red      2.99  
apple   red      2.99  
apple   red      1.99  
pear    green     .99  
pear    green     .99  
pear    green    1.29 
lemon   yellow    .99  
lemon   yellow    .99  
lemon   yellow   1.99  

(假设以上三组是来自 df 的随机组)。 我怎样才能做到这一点?我正在使用 this .但这对我的情况没有帮助。

请您参考如下方法:

您可以使用 shuffle 和 ngroup

g = df.groupby(['col1', 'col2']) 
 
a=np.arange(g.ngroups) 
np.random.shuffle(a) 
 
df[g.ngroup().isin(a[:2])]# change 2 to what you need :-)