Pandas groupby with delimiter join

后端 未结 2 2009
有刺的猬
有刺的猬 2020-11-22 00:29

I tried to use groupby to group rows with multiple values.

col val
A  Cat
A  Tiger
B  Ball
B  Bat

import pandas as pd
df = pd.read_csv(\"Inputfile.txt\", s         


        
相关标签:
2条回答
  • 2020-11-22 01:16

    Alternatively you can do it this way:

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

    UPDATE: answering question from the comment:

    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
    

    Last for convert index or MultiIndex to columns:

    df1 = df.groupby('col')['val'].agg('-'.join).reset_index(name='new')
    
    0 讨论(0)
  • 2020-11-22 01:22

    just try

    group = df.groupby(['col'])['val'].apply(lambda x: '-'.join(x))
    
    0 讨论(0)
提交回复
热议问题