Concatenate strings from several rows using Pandas groupby

后端 未结 4 1860
误落风尘
误落风尘 2020-11-22 03:17

I want to merge several strings in a dataframe based on a groupedby in Pandas.

This is my code so far:

import pandas as pd
from io import StringIO

         


        
相关标签:
4条回答
  • 2020-11-22 03:49

    You can groupby the 'name' and 'month' columns, then call transform which will return data aligned to the original df and apply a lambda where we join the text entries:

    In [119]:
    
    df['text'] = df[['name','text','month']].groupby(['name','month'])['text'].transform(lambda x: ','.join(x))
    df[['name','text','month']].drop_duplicates()
    Out[119]:
        name         text  month
    0  name1       hej,du     11
    2  name1        aj,oj     12
    4  name2     fin,katt     11
    6  name2  mycket,lite     12
    

    I sub the original df by passing a list of the columns of interest df[['name','text','month']] here and then call drop_duplicates

    EDIT actually I can just call apply and then reset_index:

    In [124]:
    
    df.groupby(['name','month'])['text'].apply(lambda x: ','.join(x)).reset_index()
    
    Out[124]:
        name  month         text
    0  name1     11       hej,du
    1  name1     12        aj,oj
    2  name2     11     fin,katt
    3  name2     12  mycket,lite
    

    update

    the lambda is unnecessary here:

    In[38]:
    df.groupby(['name','month'])['text'].apply(','.join).reset_index()
    
    Out[38]: 
        name  month         text
    0  name1     11           du
    1  name1     12        aj,oj
    2  name2     11     fin,katt
    3  name2     12  mycket,lite
    
    0 讨论(0)
  • 2020-11-22 03:54

    For me the above solutions were close but added some unwanted /n's and dtype:object, so here's a modified version:

    df.groupby(['name', 'month'])['text'].apply(lambda text: ''.join(text.to_string(index=False))).str.replace('(\\n)', '').reset_index()
    
    0 讨论(0)
  • 2020-11-22 04:00

    we can groupby the 'name' and 'month' columns, then call agg() functions of Panda’s DataFrame objects.

    The aggregation functionality provided by the agg() function allows multiple statistics to be calculated per group in one calculation.

    df.groupby(['name', 'month'], as_index = False).agg({'text': ' '.join})

    0 讨论(0)
  • 2020-11-22 04:16

    The answer by EdChum provides you with a lot of flexibility but if you just want to concateate strings into a column of list objects you can also:

    output_series = df.groupby(['name','month'])['text'].apply(list)

    0 讨论(0)
提交回复
热议问题