Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Join rows in pandas DataFrame

I have a DataFrame defined as:

test_df = pd.DataFrame(
    {"col_one": [1, 2, 3, 4, 5], "col_two": ["one", "two", "three", "four", "five"]}
).astype(str)

I am using this code to make all the rows become one single row with the values concatenated:

for c in test_df.columns:
    test_df[c] = ",".join(test_df[c].values)
print(test_df)

The result of this print statetement is this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

But the result I am looking for is this:

enter image description here

How can I achieve it?

>Solution :

I would use a self cat :

out = test_df.apply(lambda x: x.str.cat(sep=",")).to_frame().T

Or this variant with agg :

out = test_df.agg(",".join).to_frame().T

Output :

print(out)

     col_one                  col_two
0  1,2,3,4,5  one,two,three,four,five
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading