3

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.

ClaudiaR
  • 3,108
  • 2
  • 13
  • 27
  • so what is fixed is the number of words per final row? – mozway Dec 15 '22 at 14:32
  • Yes I would like to have, for example three words in each new final row, exept for the cases where there are not enough words left, in that case is okay to have a row with only one or two words. Thanks @mozway – ClaudiaR Dec 15 '22 at 14:37

1 Answers1

2

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.
mozway
  • 194,879
  • 13
  • 39
  • 75