'Pandas: How to merge all rows into a single row?

I have the following dataframe:

  text
1 "abc" 
2 "def" 
3 "ghi"
4 "jkl" 

How can I merge these rows into a dataframe with a single row like the following one?

  text 
1 "abc, def, ghi, jkl" 

Comma separation is not a must but all the values should be in a single row. The values can also be stored in a comma separated list of strings.



Solution 1:[1]

If you just want the list of values, use to_list:

sr = pd.Series(', '.join(df['text'].to_list()), name='text')

# OR

df = pd.DataFrame([', '.join(df['text'].to_list())], columns=['text'])

Output:

>>> sr
0    abc, def, ghi, jkl
Name: text, dtype: object

>>> df
                 text
0  abc, def, ghi, jkl

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Corralien