在python中的每个组上groupby之后采样

2024-09-28 19:10:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧如下:

index   accountid  transdate

0        116490  2018-10-01
1        116490  2018-07-01
2        116490  2018-09-01
3        116490  2018-08-01
4        123033  2018-10-01
5        123033  2018-07-01
6        123033  2018-09-01
7        123033  2018-08-01
8        114175  2018-10-01
9        114175  2018-07-01
10       114175  2018-09-01
11       114175  2018-08-01
12       112962  2018-10-01
13       112962  2018-07-01
14       112962  2018-09-01
15       112962  2018-08-01

我试图从每个accountid组中随机获得行数。 例如,这里每个accountid有4个transdates,我试图按accountid分组,从每个组中获得最少1行和最多4行。你知道吗

预期产量:

index    accountid  transdate

0        116490 2018-10-01
1        116490 2018-07-01
3        116490 2018-08-01
4        123033 2018-10-01
5        123033 2018-07-01
8        114175 2018-10-01
9        114175 2018-07-01
10       114175 2018-09-01
11       114175 2018-08-01
12       112962 2018-10-01
13       112962 2018-07-01
15       112962 2018-08-01

我一直按accountid分组,并对分组对象应用random.sample,但每次它都会从每个组返回固定数量的行。你知道吗


Tags: 数据sample对象数量indexrandom产量transdate
1条回答
网友
1楼 · 发布于 2024-09-28 19:10:26

您可以使用^{}获得每个类别的随机样本,并且可以设置要在1 ... min(4, len(category))中随机分布的元素数:

import random

def random_sample(x):
    n = random.randint(1, min(4, len(x)))
    return x.sample(n)

df.groupby("accountid").transdate.apply(random_sample)
# accountid    
# 112962     13    2018-07-01
#            14    2018-09-01
#            15    2018-08-01
# 114175     10    2018-09-01
#            11    2018-08-01
# 116490     2     2018-09-01
#            0     2018-10-01
#            3     2018-08-01
# 123033     5     2018-07-01
#            4     2018-10-01
#            7     2018-08-01

相关问题 更多 >