![](/img/trans.png)
[英]How to count number of rows per group greater than the average of that group in pandas group by?
[英]How to randomly select fixed number of rows (if greater) per group else select all rows in pandas?
示例数据框:
Name Group_Id
AAA 1
ABC 1
BDF 1
CCC 2
XYZ 2
DEF 3
如何为每个Group_Id
随机选择固定数量的行? 这个答案提出了一种使用方法:
df.groupby('Group_Id').apply(lambda x: x.sample(2)).reset_index(drop=True)
但是如果有任何少于2
行的组,它会引发错误。 在这种情况下,我希望能够选择所有行。 .head()
允许这样做,但我想要随机样本而不是初始行。
假设我希望每个Group_Id
最多随机抽取Group_Id
,我会得到:
Name Group_Id
AAA 1
BDF 1
CCC 2
XYZ 2
DEF 3
仅当您有更多行时,您才可以选择采样:
n = 2
(df.groupby('Group_Id')
.apply(lambda x: x.sample(n) if len(x)>n else x )
.reset_index(drop=True)
)
您还可以尝试对整个数据和groupby().head()
混洗:
df.sample(frac=1).groupby('Group_Id').head(2)
输出:
Name Group_Id
5 DEF 3
0 AAA 1
2 BDF 1
3 CCC 2
4 XYZ 2
您可以洗牌每个子组并取前 n 行。 它将自动取 n 或实际的最小值。
n=2
df2 = df.groupby('Group_Id').apply(lambda x: x.sample(frac=1)[:n]).reset_index(drop=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.