Pandas按唯一值分组并对其进行平均

6

我有以下数据框:

   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

我想做的是按IDID2分组,并仅考虑唯一的分数平均SCORE
现在,如果我使用标准的df.groupby(['ID', 'ID2'])['SCORE'].mean(),我将得到23.33~的分数,而我要找的是25分。
我知道我可以过滤掉XY,去除重复项并这样做,但我想保留它们,因为它们是相关的。
我该如何实现?
3个回答

11

如果我理解正确:

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

应该是25,而不是35,因为20和30的平均值是25。 - bluesummers
1
lambda x: x.unique().sum()/x.nunique()) 确实有效! - bluesummers
@bluesummers,是的,我也得出了同样的解决方案... :-) - MaxU - stand with Ukraine

2

在处理前先删除重复项,可以获取('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

1

您也可以使用

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接