novastar
novastar

Reputation: 166

Convert all rows of a Pandas 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 this 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'"

Upvotes: 0

Views: 2274

Answers (4)

anky
anky

Reputation: 75080

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

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

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

Upvotes: 2

mullinscr
mullinscr

Reputation: 1738

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'"

Upvotes: 0

BENY
BENY

Reputation: 323306

A quick fix will be

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

Upvotes: 3

gtomer
gtomer

Reputation: 6564

Try this:

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

Upvotes: 0

Related Questions