首页 > 解决方案 > 使用 pandas 从每个组中随机选择一行

问题描述

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

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

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

其中mnthShape值是从索引中随机选择的。即,如果查询是 df.loc[(1, 1)] 它应该查找 (1, 1) 的所有值并从中随机选择要在上面显示的值。

标签: pythonpandasdataframerandom

解决方案


一种方法是Series.sample()从每组中随机抽取一行:

pd.np.random.seed(1)

res = df.groupby(['Month', 'Day'])['mnthShape'].apply(lambda x: x.sample()).reset_index(level=[0, 1])

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

推荐阅读