The Great
The Great

Reputation: 7723

Convert multiple rows of text into a Single row using Pandas

I have a dataframe like as shown below

df = pd.DataFrame({'text': ["Hi how are you","I am fine","I love you","I hate you"]})

I would like to convert all these individual rows into a single row

I tried the below but it is incorrect and doesn't work

df['text'].apply(' '.join).reset_index()

I expect my output to be like as shown below

enter image description here

How can I do this?

Upvotes: 1

Views: 637

Answers (1)

Anurag Dabas
Anurag Dabas

Reputation: 24314

try via agg(),to_frame() and reset_index():

out=(df.agg(' '.join)
        .to_frame('text')
        .reset_index(drop=True))

output of out:

    text
0   Hi how are you I am fine I love you I hate you

Upvotes: 3

Related Questions