使用 Pandas GroupBy 找到每个组的一半

Arn*_*ein 6 python pandas split-apply-combine pandas-groupby

我需要使用 选择数据框的一半groupby,其中每个组的大小未知并且可能因组而异。例如:

       index  summary  participant_id
0     130599     17.0              13
1     130601     18.0              13
2     130603     16.0              13
3     130605     15.0              13
4     130607     15.0              13
5     130609     16.0              13
6     130611     17.0              13
7     130613     15.0              13
8     130615     17.0              13
9     130617     17.0              13
10     86789     12.0              14
11     86791      8.0              14
12     86793     21.0              14
13     86795     19.0              14
14     86797     20.0              14
15     86799      9.0              14
16     86801     10.0              14
20    107370      1.0              15
21    107372      2.0              15
22    107374      2.0              15
23    107376      4.0              15
24    107378      4.0              15
25    107380      7.0              15
26    107382      6.0              15
27    107597      NaN              15
28    107384     14.0              15
Run Code Online (Sandbox Code Playgroud)

从组的大小groupyby('participant_id')是10,7,9为participant_id13,14,15分别。我需要的是只取每组的前半部分(或楼层(N/2))。

从我对 Pandas 的(非常有限的)经验来看groupby,它应该是这样的:

df.groupby('participant_id')[['summary','participant_id']].apply(lambda x: x[:k_i])
Run Code Online (Sandbox Code Playgroud)

其中k_i是每组大小的一半。有没有一个简单的解决方案来找到k_i

Sco*_*ton 6

IIUC,您可以在 lambda 内部使用大小为 //2 的索引切片:

df.groupby('participant_id').apply(lambda x: x.iloc[:x.participant_id.size//2])
Run Code Online (Sandbox Code Playgroud)

输出:

                    index  summary  participant_id
participant_id                                    
13             0   130599     17.0              13
               1   130601     18.0              13
               2   130603     16.0              13
               3   130605     15.0              13
               4   130607     15.0              13
14             10   86789     12.0              14
               11   86791      8.0              14
               12   86793     21.0              14
15             20  107370      1.0              15
               21  107372      2.0              15
               22  107374      2.0              15
               23  107376      4.0              15
Run Code Online (Sandbox Code Playgroud)

  • 不错的答案,您可能还想考虑在 `.groupby()` 中设置 `as_index=False`。 (2认同)