Pandas groupby:将不同的值组合到另一列中

2024-04-19 20:21:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要按列的子集进行分组,并计算它们的值的不同组合的数量。但是,还有其他列可能有不同的值,也可能没有不同的值,我希望以某种方式在输出中保留这些信息。举个例子:

gb1          gb2         text1   text2
bebop        skeletor    blue    fisher
bebop        skeletor    blue    wright
rocksteady   beast_man   orange  haldane
rocksteady   beast_man   orange  haldane
tokka        kobra_khan  green   lande
tokka        kobra_khan  red     arnold

我只想按gb1gb2分组。你知道吗

我需要的是:

gb1          gb2         count   text1        text2
bebop        skeletor    2       blue         fisher, wright
rocksteady   beast_man   2       orange       haldane
tokka        kobra_khan  2       green, red   lande, arnold

除了处理text1text2列之外,我的一切都正常。你知道吗

提前谢谢。你知道吗


Tags: blueorangemankhantext1bebopbeastskeletor
2条回答

可以使用applytransform的组合:

如果df是原始数据帧:

def combine(xx):
    dd = xx.transform(lambda x : ','.join(set(x)))
    dd['count'] = len(xx)
    return dd

ddf = df.groupby(['gb1', 'gb2']).apply(combine)

对于示例数据帧,ddf是:

                           text1          text2  count
gb1        gb2                                        
bebop      skeletor         blue  fisher,wright      2
rocksteady beast_man      orange        haldane      2
tokka      kobra_khan  red,green   lande,arnold      2

你可以和我核对一下

s=df.assign(count=1).groupby(['gb1','gb2']).agg({'count':'sum','text1':lambda x : ','.join(set(x)),'text2':lambda x : ','.join(set(x))}).reset_index()
s
          gb1         gb2  count      text1          text2
0       bebop    skeletor      2       blue  wright,fisher
1  rocksteady   beast_man      2     orange        haldane
2       tokka  kobra_khan      2  green,red   lande,arnold

相关问题 更多 >