5

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

1
  • df['Name'].str.cat(sep=',') Commented Aug 20, 2019 at 2:40

7 Answers 7

13

Try:

st = ','.join(df["Name"])
Sign up to request clarification or add additional context in comments.

2 Comments

oh it's good than my code cause won't have to turn to list :D cool man!
Do note, that @Robert Price's solution is brittle.
2
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

Comments

2

Try This

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

Comments

1

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.

1 Comment

this will output as a column
1

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)

Comments

1

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

Comments

0

For single column you can use:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.