asmgx
asmgx

Reputation: 8054

Python DataFrame Column to a comma separated value string

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

Upvotes: 5

Views: 11999

Answers (7)

VHS
VHS

Reputation: 10194

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"]))

Upvotes: 1

Ricky
Ricky

Reputation: 134

For single column you can use:

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

Upvotes: 0

Hamza Lachi
Hamza Lachi

Reputation: 1064

Try This

var_name = ','.join(df["Name"])

Upvotes: 2

hmanolov
hmanolov

Reputation: 113

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)

Upvotes: 1

hd1
hd1

Reputation: 34677

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.

Upvotes: 1

Thotsaphon Sirikutta
Thotsaphon Sirikutta

Reputation: 128

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

Upvotes: 2

Robert Price
Robert Price

Reputation: 641

Try:

st = ','.join(df["Name"])

Upvotes: 13

Related Questions