Starbucks
Starbucks

Reputation: 1568

Combining multiple Rows into one Row one Column Python

I need to combine all the rows for a dataframe into one row in one column. For example:

data = ('Hello', 'are you having','', 
        'a nice day today? I am very', 
        'delighted to have snail as','',
        'my','','entree for dinner tonight.')

data = pd.DataFrame(list(data))

Returns:

print(data)
                             0
0                        Hello
1               are you having
2                             
3  a nice day today? I am very
4     delighted to have snail as
5                             
6                           my
7                             
8   entree for dinner tonight.

Now I'll try to combine all rows into one column:

data = data.rename(columns={0: 'value'})
data = data.groupby('value').apply(' '.join).reset_index()

This will create an additional column with the string "value" for every row. Any help would be appreciated.

Upvotes: 0

Views: 2387

Answers (1)

LazyCoder
LazyCoder

Reputation: 1265

Hope this is what you've wanted.

import pandas as pd
data = ('Hello', 'are you having','', 
        'a nice day today? I am very', 
        'delighted to have snail as','',
        'my','','entree for dinner tonight.')

data = pd.DataFrame(list(data))
data = data.rename(columns={0: 'value'})
data['new'] = data['value'].str.cat(sep=' ')#concatenate all the strings in existing column and create a new one.
print(data)

Output:


                                                 new  
0  Hello are you having  a nice day today? I am v...  
1  Hello are you having  a nice day today? I am v...  
2  Hello are you having  a nice day today? I am v...  
3  Hello are you having  a nice day today? I am v...  
4  Hello are you having  a nice day today? I am v...  
5  Hello are you having  a nice day today? I am v...  
6  Hello are you having  a nice day today? I am v...  
7  Hello are you having  a nice day today? I am v...  
8  Hello are you having  a nice day today? I am v...  

Upvotes: 1

Related Questions