Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 聚合列上的合并_Python_Pandas - Fatal编程技术网

Python 聚合列上的合并

Python 聚合列上的合并,python,pandas,Python,Pandas,假设我创建了一个数据帧: 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 。。。然后通过几列

假设我创建了一个数据帧:

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
不是一列。所以我的问题有两个:

  • 我是否可以将
    gb
    数据帧的多索引转换回列(以便它具有
    b
    c
    列)
  • 我可以在列名上将
    df
    gb
    合并吗

  • 有一种简单的方法可以使用
    reset\u index()
    执行此操作

    给你

       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时,这将生成一个系列,其索引与您的原始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
    

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

    @EdChum的方法远远优于我的方法。是否可以将
    agg
    的结果放入一个新列中,以便合并不会重命名列?我想,使用
    reset_index
    的优点是,聚合表中的行数对应于聚合键的数量(即,['b','c']),我可能想保留它,以便在合并之后进行进一步分析。@juniper-您必须重命名发生冲突的列名,以便合并不添加后缀。您可以将groupby对象存储为一个变量,它只是一个描述groupby应该如何执行的对象,这样做不会造成性能损失this@juniper如上所述,您必须手动重命名列以删除后缀。看这里-->谢谢你们!我希望我能接受你的两个答案,因为它们都很有帮助,但是Ed因为效率得到了蛋糕。这太棒了。比我的解决方案优雅得多。同意-@aus_lacy的回答解决了OP的问题,但这是一种更好的方法。我们可以在几个操作上做到这一点:count/sum/etc。。。每个操作都有一个自动的新列?
    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