假设我有一个看起来像这样的数据框:
Name Group_Id
AAA 1
ABC 1
CCC 2
XYZ 2
DEF 3
YYH 3
如何为每个 Group_Id
随机选择一个(或多个)行?假设我希望每个 Group_Id
随机抽取一次,我会得到:
Name Group_Id
AAA 1
XYZ 2
DEF 3
最佳答案
从 0.16.x
开始 pd.DataFrame.sample
提供了一种从对象轴返回随机项目样本的方法。
In [664]: df.groupby('Group_Id').apply(lambda x: x.sample(1)).reset_index(drop=True)
Out[664]:
Name Group_Id
0 ABC 1
1 XYZ 2
2 DEF 3
关于Python:每组随机选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22472213/