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

标签 python pandas

我有一个非常大的 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 .但这对我的情况没有帮助。

最佳答案

您可以使用 shufflengroup

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 :-) 

关于python - 在 pandas 的 groupby 之后选择样本随机组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50004641/

相关文章:

python - pygame中 "x"和 "y"中的独立 Sprite 运动

python - one-hot 编码 : list of column_values has to encode

python Pandas : replace values based on location not index value

json - pandas json_normalize 展平嵌套字典

围绕枚举的 Pythonic 方式

python - 类型错误 : 'CommandCursor' object has no attribute '__getitem__'

python - 如何执行在Python循环中迭代的元素总和

python - BeautifulSoup 在 findAll 中排除一个标签

pandas - 如何将 lambda 函数正确应用到 Pandas 数据框列中

python - 如何创建一个具有一个索引键列和多个值列的字典