0

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.

Daniel
  • 183
  • 8

2 Answers2

3

Try this:

df = pd.DataFrame({'text': [', '.join(df['text'].str.strip('"').tolist())]})

Output:

>>> df
                 text
0  abc, def, ghi, jkl
richardec
  • 14,202
  • 6
  • 23
  • 49
2

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
Corralien
  • 70,617
  • 7
  • 16
  • 36