Pandas groupby 和唯一值的平均值

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

我想做的是对 IDID2 进行分组,并在仅考虑 UNIQUE 分数的情况下对 SCORE 进行平均。

现在,如果我使用标准 df.groupby(['ID', 'ID2'])['SCORE'].mean(),我会得到 23.33~,我要找的是 25 分。

我知道我可以过滤掉 XY,删除重复项并执行此操作,但我想保留它们的相关性。

我怎样才能做到这一点?

如果我没理解错的话:

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