[英]average aggregation in pandas groupby while considering unique values of a column
[英]Pandas groupby and average across unique values
我有以下數據框
ID ID2 SCORE X Y
0 0 a 10 1 2
1 0 b 20 2 3
2 0 b 20 3 4
3 0 b 30 4 5
4 1 c 5 5 6
5 1 d 6 6 7
我想做的是對ID
和ID2
進行分組,並在僅考慮 UNIQUE 分數的情況下對SCORE
進行平均。
現在,如果我使用標准df.groupby(['ID', 'ID2'])['SCORE'].mean()
我會得到 23.33~,我正在尋找的分數是 25。
我知道我可以過濾掉X
和Y
,刪除重復項並這樣做,但我想保留它們,因為它們是相關的。
我怎樣才能做到這一點?
如果我理解正確:
In [41]: df.groupby(['ID', 'ID2'])['SCORE'].agg(lambda x: x.unique().sum()/x.nunique())
Out[41]:
ID ID2
0 a 10
b 25
1 c 5
d 6
Name: SCORE, dtype: int64
或者更簡單:
In [43]: df.groupby(['ID', 'ID2'])['SCORE'].agg(lambda x: x.unique().mean())
Out[43]:
ID ID2
0 a 10
b 25
1 c 5
d 6
Name: SCORE, dtype: int64
您可以通過預先刪除重復項來獲得('ID', 'ID2')
組內的唯一分數。
cols = ['ID', 'ID2', 'SCORE']
d1 = df.drop_duplicates(cols)
d1.groupby(cols[:-1]).SCORE.mean()
ID ID2
0 a 10
b 25
1 c 5
d 6
Name: SCORE, dtype: int64
你也可以用
In [108]: df.drop_duplicates(['ID', 'ID2', 'SCORE']).groupby(['ID', 'ID2'])['SCORE'].mean()
Out[108]:
ID ID2
0 a 10
b 25
1 c 5
d 6
Name: SCORE, dtype: int64
這些代碼還給出了確切的值......這是一個正確的方法......!!!!??
df.groupby(["ID","ID2"])["Score"].mean()
ID ID2
0 a 10.000000
b 23.333333
1 c 5.000000
d 6.000000
Name: Score, dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.