How to combine multiple rows of strings into one using pandas?

前端 未结 4 1522
情话喂你
情话喂你 2021-02-01 19:12

I have a DataFrame with multiple rows. Is there any way in which they can be combined to form one string?

For example:

     words
0    I, will, hereby
1         


        
4条回答
  •  無奈伤痛
    2021-02-01 19:32

    How about traditional python's join? And, it's faster.

    In [209]: ', '.join(df.words)
    Out[209]: 'I, will, hereby, am, gonna, going, far, to, do, this'
    

    Timings in Dec, 2016 on pandas 0.18.1

    In [214]: df.shape
    Out[214]: (6, 1)
    
    In [215]: %timeit df.words.str.cat(sep=', ')
    10000 loops, best of 3: 72.2 µs per loop
    
    In [216]: %timeit ', '.join(df.words)
    100000 loops, best of 3: 14 µs per loop
    
    In [217]: df = pd.concat([df]*10000, ignore_index=True)
    
    In [218]: df.shape
    Out[218]: (60000, 1)
    
    In [219]: %timeit df.words.str.cat(sep=', ')
    100 loops, best of 3: 5.2 ms per loop
    
    In [220]: %timeit ', '.join(df.words)
    100 loops, best of 3: 1.91 ms per loop
    

提交回复
热议问题