Home > OS >  Split text in column into multiple rows each containing the same number of words
Split text in column into multiple rows each containing the same number of words

Time:12-16

Let's say I have the following dataframe:

import pandas as pd

data = [
        ["a", "Lorem ipsum dolor sit amet, consectetur adipiscing elit."],
        ["b", "Etiam imperdiet fringilla est, eu tristique risus varius vitae."]
       ]
df = pd.DataFrame(data, columns=['name', 'text'])

>>    name   text
>> 0    a    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
>> 1    b    Etiam imperdiet fringilla est, eu tristique risus varius vitae.

I would like to generate the following dataframe:

name                       text
0    a          Lorem ipsum dolor
1    a      sit amet, consectetur
2    a           adipiscing elit.
3    b  Etiam imperdiet fringilla
4    b          est, eu tristique
5    b        risus varius vitae.

To be more clear, I would like to split each string at column "text" over multiple rows. The number of rows depends on the number of words in each string. In the example I provided I have chosen three as number of words in each row. The values contained inside the other columns should be kept.

Also the last new row of the "a" original row, contains only two words, because those are the only words left.

I found a similar question, which, however, splits the text over multiple columns. I'm not sure how to adapt it to split over rows.

CodePudding user response:

Use a regex with str.findall to find chunks of up to 3 words, then explode:

out = (df.assign(text=df['text'].str.findall(r'(?:\S \s ){1,3}'))
         .explode('text')
       )

Output:

  name                        text
0    a          Lorem ipsum dolor 
0    a      sit amet, consectetur 
0    a                 adipiscing 
1    b  Etiam imperdiet fringilla 
1    b          est, eu tristique 
1    b               risus varius 

regex demo

Or, to avoid the trailing spaces:

out = (df.assign(text=df['text'].str.findall(r'(?:\S \s ){1,2}\S '))
         .explode('text')
       )

Output:

  name                       text
0    a          Lorem ipsum dolor
0    a      sit amet, consectetur
0    a           adipiscing elit.
1    b  Etiam imperdiet fringilla
1    b          est, eu tristique
1    b        risus varius vitae.
  • Related