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
Answers:
Try:
st = ','.join(df["Name"])
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.
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)
Try This
var_name = ','.join(df["Name"])
For single column you can use:
"'"+DataFram.Column.map(lambda x:
x.strip()).to_string(index=False).replace('n',"','")+"'"
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"]))
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
Try:
st = ','.join(df["Name"])
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.
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)
Try This
var_name = ','.join(df["Name"])
For single column you can use:
"'"+DataFram.Column.map(lambda x:
x.strip()).to_string(index=False).replace('n',"','")+"'"
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"]))