Reputation: 8054
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
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
Reputation: 134
For single column you can use:
"'"+DataFram.Column.map(lambda x:
x.strip()).to_string(index=False).replace('\n',"','")+"'"
Upvotes: 0
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
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
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())
Upvotes: 2