Convert all rows of a padas dataframe column to comma separated values with each value in single quote

I have a pandas dataframe similar to:

df = pd.DataFrame(['a', 'b', 'c', 'd'], columns=['Col'])

df 

Col
0   a
1   b
2   c
3   d

I am trying to convert all rows of this column to a comma separated string with each value in single quotes, like below:

'a', 'b', 'c', 'd'

I have tried the following with several different combinations but below is the closest I got:

s = df['Col'].str.cat(sep="', '")
s
"a', 'b', 'c', 'd"

I think that the end result should be:

"'a', 'b', 'c', 'd'"

Any help is highly appreciated.

4 answers

  • answered 2020-09-24 15:54 gtomer

    Try this:

    s = df['Col'].tolist()
    

  • answered 2020-09-24 15:54 BEN_YO

    A quick fix will be

    "'" + df['Col1'].str.cat(sep="', '") + "'"
    "'a', 'b', 'c', 'd'"
    

  • answered 2020-09-24 15:56 mullinscr

    Try something like this:

    df = pd.DataFrame(['a', 'b', 'c', 'd'], columns=['Col1'])
    
    values = df['Col1'].to_list()
    with_quotes = ["'"+x+"'" for x in values]
    ','.join(with_quotes)
    

    Output:

    "'a','b','c','d'"

  • answered 2020-09-24 15:59 anky

    another alternative is adding each element with an extra quote and then use default .join;

    ', '.join([f"'{i}'" for i in df['Col1']])
    

    "'a', 'b', 'c', 'd'"