![](/img/trans.png)
[英]Pandas groupby - apply different functions to half the records in each group
[英]Find half of each group with 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
組從尺寸groupyby('participant_id')
是10,7,9為participant_id
13,14,15分別。 我需要的只是每組的第一半(或樓板數(N / 2))。
根據我對Pandas groupby
經驗(非常有限),應該是這樣的:
df.groupby('participant_id')[['summary','participant_id']].apply(lambda x: x[:k_i])
其中k_i
是每組大小的一半。 有找到k_i
的簡單解決方案嗎?
IIUC,您可以在lambda內部使用大小為// 2的索引切片:
df.groupby('participant_id').apply(lambda x: x.iloc[:x.participant_id.size//2])
輸出:
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
您可以按participant_id
ID分組,並使用transform
方法檢查其索引是否在前半部分。 這將創建一個布爾系列。 然后使用此布爾系列過濾掉原始數據框。
criteria = df.groupby('participant_id')['participant_id']\
.transform(lambda x: np.arange(len(x)) < int(len(x) / 2))
df[criteria]
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
10 86789 12.0 14
11 86791 8.0 14
12 86793 21.0 14
20 107370 1.0 15
21 107372 2.0 15
22 107374 2.0 15
23 107376 4.0 15
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.