Skip to content
Advertisement

Pandas join rows of text and output as a new variable

Given following DF

    0
0   Maintain the distance.
1   Ensure it is checked.
2   Inbetween distance must be 0.5.
3   Take extra notes of the distance.

Is it possible for Pandas to join all rows, give a new line and return the result as a variable?

Final output:

Variable n:

Maintain the distance.

Ensure it is checked.

Inbetween distance must be 0.5.

Take extra notes of the distance.

I have explored str.cat() but seem like the separator do not allow a n.

Advertisement

Answer

Use as many n newlines as you like.

>>> df = pd.DataFrame(dict(word='a man a plan a canal'.split()))
>>> df
    word
0      a
1    man
2      a
3   plan
4      a
5  canal
>>> 
>>> text = df.word.str.cat(sep='nn')
>>> print(text)
a

man

a

plan

a

canal
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement