Home > Blockchain >  Pandas join rows of text and output as a new variable
Pandas join rows of text and output as a new variable

Time:09-04

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.

CodePudding user response:

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='\n\n')
>>> print(text)
a

man

a

plan

a

canal

CodePudding user response:

You could join the values:

df = pd.DataFrame({0: ['Maintain the distance.', 'Ensure it is checked.', 'Inbetween distance must be 0.5.', 'Take extra notes of the distance.']})
all = '\n'.join(df[0].values)
print(all)

Output:

Maintain the distance.
Ensure it is checked.
Inbetween distance must be 0.5.
Take extra notes of the distance.
  • Related