Home > Software design >  convert column to comma seperarted string with python
convert column to comma seperarted string with python

Time:05-20

I have a data frame as:

id.      name
123      sanfrancisco
124      losangeles
12356    washington  
123441   orlando

I need to convert this name column into comma sep string value as:

'san francisco', 'losangeles', 'washington', 'orlando'

I've changed this into list but i cannot use array, i need string value.

thanks

CodePudding user response:

', '.join(df.name.to_list())

 'sanfrancisco, losangeles, washington, orlando'

CodePudding user response:

Do you want to convert it to csv? If so you could directly use the to_csv method. Otherwise, to get the exact string you mentioned you could do:

name = df.name.tolist()
string = "'"   name[0] "'"
for n in name[1:]:
  string  = ", '"   n   "'"

Output:

'sanfrancisco', 'losangeles', 'washington', 'orlando'
  • Related