Pandas 在聚合列上合并

Pandas merge on aggregated columns

假设我创建了一个 DataFrame:

import pandas as pd
df = pd.DataFrame({"a": [1,2,3,13,15], "b": [4,5,6,6,6], "c": ["wish", "you","were", "here", "here"]})

像这样:

    a   b   c
0   1   4   wish
1   2   5   you
2   3   6   were
3   13  6   here
4   15  6   here

...然后按几列进行分组和聚合...

gb = df.groupby(['b','c']).agg({"a": lambda x: x.nunique()})

产生以下结果:

            a
b   c   
4   wish    1
5   you     1
6   here    2
    were    1

是否可以将 df 与新聚合的 table gb 合并,以便我在 df 中创建一个新列,其中包含来自 gb 的相应值?像这样:

    a   b   c      nc
0   1   4   wish    1
1   2   5   you     1
2   3   6   were    1
3   13  6   here    2
4   15  6   here    2

我尝试做最简单的事情:

df.merge(gb, on=['b','c'])

但这给出了错误:

KeyError: 'b'

这是有道理的,因为分组的 table 有一个多索引,而 b 不是一个列。所以我的问题有两个:

  1. 我能否将 gb DataFrame 的多索引转换回列(使其具有 bc 列)?
  2. 我可以在列名上合并 dfgb 吗?

使用 reset_index() 有一种简单的方法可以做到这一点。

df.merge(gb.reset_index(), on=['b','c'])

给你

   a_x  b    c    a_y
0    1  4  wish    1
1    2  5   you    1
2    3  6  were    1
3   13  6  here    2
4   15  6  here    2

每当您想将一些聚合列从 groupby 操作添加回 df 时,您应该使用 transform,这会生成一个系列,其索引与您的原始 df:

In [4]:

df['nc'] = df.groupby(['b','c'])['a'].transform(pd.Series.nunique)
df
Out[4]:
    a  b     c  nc
0   1  4  wish   1
1   2  5   you   1
2   3  6  were   1
3  13  6  here   2
4  15  6  here   2

无需重置索引或执行额外的合并。