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:
But the result I am looking for is this:
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