Let's suppose that I have the following in a DataFrame
in pandas
:
id text
1 I am the first document and I am very happy.
2 Here is the second document and it likes playing tennis.
3 This is the third document and it looks very good today.
and I want to split the text of each id in tokens of 3 words so I finally want to have the following:
id text
1 I am the
1 first document and
1 I am very
1 happy
2 Here is the
2 second document and
2 it likes playing
2 tennis
3 This is the
3 third document and
3 it looks very
3 good today
Keep in mind that my dataframe may also have other columns except for these two which should be simply copied at the new dataframe in the same way as id
above.
What is the most efficient way to do this?
I reckon that the solution to my question is quite close to the solution given here: Tokenise text and create more rows for each row in dataframe.
This may help too: Python: Split String every n word in smaller Strings.