Python DataFrame Column to a comma separated value string

Question:

First I have searched Stakeoverflow and googled

but I got was how to join columns with comma for the same record or how to convert CSV to dataframe

My Dataset looks like this

ID     Name
1      Tom
2      John
3      Mike
4      Nancy

I want to get a string that has all Names with comma in between them

st = "Tom,John,Mike,Nancy"

I tried this code but doesn’t give me the results I expected

st = df["Name"].to_string()

How can I do that

Asked By: asmgx

||

Answers:

Try:

st = ','.join(df["Name"])
Answered By: Robert Price
df[my_columns].tolist()

will be transform pd.Series to list python

and then using normal python to join list to string

','.join(df[my_columns].tolist())

enter image description here

Answered By: CelastrinaLadon

df[‘Name’] is a Series. These objects have a to_csv method. Essentially, you’ll do something akin to:

out = df['Name'].to_csv(path_of_buf=None, header=False, index=False)

Hope it helps.

Answered By: hd1

You could either look into listagg on a df field. This link should provide you with a snippet that can help.

Or simply join a string of comma to the series itself…

','.join(dataframe['column'].tolist())

or

dataframe['column'].to_csv(header=False)
Answered By: hmanolov

Try This

var_name = ','.join(df["Name"])
Answered By: Hamza Lachi

For single column you can use:

"'"+DataFram.Column.map(lambda x: 
x.strip()).to_string(index=False).replace('n',"','")+"'"
Answered By: Ricky

If your dataframe column that you want to get a comma separated string out of contains numbers, you might want to first map the cells to string like so:

st = ','.join(map(str, df["Col1"]))

Answered By: VHS
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.