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

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)

The result of this print statetement is this:

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:",")).to_frame().T

Or this variant with agg :

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

Output :


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

Leave a Reply