python - Pandas 在聚合列上合并

标签 python pandas

假设我创建了一个 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使用新聚合表 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'

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

  1. 我可以转换 gb 的多索引吗? DataFrame 回到列中(以便它具有 bc 列)?
  2. 我可以合并吗 dfgb在列名上?

最佳答案

每当你想从 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

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

关于python - Pandas 在聚合列上合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28345724/

相关文章:

python - 两个客户端无法在套接字客户端-服务器连接中相互通信

python-3.x - 公式缺少参数的 Statsmodels GLM 和 OLS

python - 如何使用 fill_between 按月创建最小-最大图

python - 访问 Pandas 数据框列的正确方法

python - 绘制排除 pandas 或 matplotlib 中缺失值的图表

python - 如何在Python中从原始数据和列中查找索引?

python - 多面体/点集中的最大内接椭圆体

python - Whit python,在 blender 中插入一个效果条作为视频序列编辑器中的删除

python - 从分组列中另一个 DataFrame 的每一行创建 DataFrame?

Python 按一列分组并计算另一列的百分比