![](/img/trans.png)
[英]How to convert GroupBy object in pandas to multiindexed dataframe
[英]How to filter the groupby dataframe in a multiindexed data
我有一個這樣的數據框:
df:
ID Group Score1
1 A 45
2 A 12
3 B 33
3 C 64
. . .
. . .
15000 . .
有數千個重復的 ID,總共 15 個組。 對於每個組,我想顯示
所以我的 output 看起來像這樣:Output:
Group No of unique No of unique No of unique No of unique
IDs >= Median IDs > 40 IDs below IDs above the
first quartile third quartile
A 56 25 17 45
B 33 78 28 62
C 23 36 38 33
.
.
P 39 28 26 41
誰能幫我這個? 非常感謝!
希望這有效。 首先我先在原來的dataframe中創建了四個對應的列。 然后創建df1
,它是具有唯一 ID 的 dataframe df
。 最后,使用pd.groupby()
可以創建所需的 output:
df = pd.DataFrame({'ID': list(range(100)),
'Group': list('ABCDE')*20,
'Score1': np.random.randint(10, 99, 100)})
df['No of unique IDs >= Median'] = df.Score1 >= df.Score1.median()
df['No of unique IDs > 40'] = df.Score1 > 40
df['No of unique IDs < first quartile'] = df.Score1 < df.Score1.quantile(0.25)
df['No of unique IDs > third quartile'] = df.Score1 > df.Score1.quantile(0.75)
df1 = df.groupby(['ID', 'Group']).any().reset_index()
df1.groupby('Group').agg({'No of unique IDs >= Median': 'sum',
'No of unique IDs > 40': 'sum',
'No of unique IDs < first quartile': 'sum',
'No of unique IDs > third quartile': 'sum'})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.