【问题标题】:Pandas groupby with delimiter join带有分隔符的 Pandas groupby 连接
【发布时间】:2021-06-08 12:00:09
【问题描述】:

我尝试使用 groupby 对具有多个值的行进行分组。

col val
A  Cat
A  Tiger
B  Ball
B  Bat

import pandas as pd
df = pd.read_csv("Inputfile.txt", sep='\t')
group = df.groupby(['col'])['val'].sum()

我明白了

A CatTiger
B BallBat

我想引入一个分隔符,让我的输出看起来像

A Cat-Tiger
B Ball-Bat

我试过了,

group = df.groupby(['col'])['val'].sum().apply(lambda x: '-'.join(x))

这成功了,

A C-a-t-T-i-g-e-r
B B-a-l-l-B-a-t

这里有什么问题?

谢谢,

AP

【问题讨论】:

    标签: python python-3.x pandas pandas-groupby


    【解决方案1】:

    试试吧

    group = df.groupby(['col'])['val'].apply(lambda x: '-'.join(x))
    

    【讨论】:

      【解决方案2】:

      您也可以这样做:

      In [48]: df.groupby('col')['val'].agg('-'.join)
      Out[48]:
      col
      A    Cat-Tiger
      B     Ball-Bat
      Name: val, dtype: object
      

      更新:回答评论中的问题:

      In [2]: df
      Out[2]:
        col    val
      0   A    Cat
      1   A  Tiger
      2   A  Panda
      3   B   Ball
      4   B    Bat
      5   B  Mouse
      6   B    Egg
      
      In [3]: df.groupby('col')['val'].agg('-'.join)
      Out[3]:
      col
      A       Cat-Tiger-Panda
      B    Ball-Bat-Mouse-Egg
      Name: val, dtype: object
      

      将索引或多索引转换为列的最后一个:

      df1 = df.groupby('col')['val'].agg('-'.join).reset_index(name='new')
      

      【讨论】:

      • 一次将多于两行连接在一起时是否有效?我尝试使用换行符连接行,结果是前两行用新行连接,其余的连接在一起没有分隔符。
      • 添加了reset_index,因为this,可以免费修改答案。
      【解决方案3】:

      你可以先聚合到list再加入str.join

      df = pd.DataFrame({'A': [1, 1, 1, 2, 2, 2], 'B': ['a', 'b', 'c', 'd', 'e', 'f']})
      
      df.groupby('A')['B'].agg(list).str.join('-')
      

      输出:

      A
      1    a-b-c
      2    d-e-f
      Name: B, dtype: object
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-01
        相关资源
        最近更新 更多