Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading