使用 pandas 从每个组中随机选择一行 [英] Randomly select a row from each group using pandas

查看:131
本文介绍了使用 pandas 从每个组中随机选择一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框df,它显示如下:

I have a pandas dataframe df which appears as following:

Month   Day mnthShape
1      1    1.016754224
1      1    1.099451003
1      1    0.963911929
1      2    1.016754224
1      1    1.099451003
1      2    0.963911929
1      3    1.016754224
1      3    1.099451003
1      3    1.783775568

我想从df中获得以下信息:

I want to get the following from df:

Month   Day mnthShape
1       1   1.016754224
1       2   1.016754224
1       3   1.099451003

其中,mnthShape值是从索引中随机选择的.也就是说,如果查询为df.loc [(1,1)],则应查找(1,1)的所有值,然后从中随机选择一个要在上方显示的值.

where the mnthShape values are selected at random from the index. i.e. if the query is df.loc[(1, 1)] it should look for all values for (1, 1) and select randomly from it a value to be displayed above.

推荐答案

使用groupbyapply在每个组中随机选择一行.

Use groupby with apply to select a row at random per group.

np.random.seed(0)
df.groupby(['Month', 'Day'])['mnthShape'].apply(np.random.choice).reset_index()

   Month  Day  mnthShape
0      1    1   1.016754
1      1    2   0.963912
2      1    3   1.099451

如果您想知道采样行来自哪个索引,请将pd.Series.samplen=1结合使用:

If you want to know what index the sampled rows come from, use pd.Series.sample with n=1:

np.random.seed(0)
(df.groupby(['Month', 'Day'])['mnthShape']
   .apply(pd.Series.sample, n=1)
   .reset_index(level=[0, 1]))

   Month  Day  mnthShape
2      1    1   0.963912
3      1    2   1.016754
6      1    3   1.016754

这篇关于使用 pandas 从每个组中随机选择一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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