Pandas dataframe rows merge by date in a single row

Question:

Given the following pandas dataframe as example:

date,test
2022-09-01,demo1
2022-09-01,demo2
2022-09-01,demo3
2022-09-02,demo4
2022-09-02,demo5
2022-09-02,demo6

I would like convert to this dataframe where each value of ‘date’ is unique and all columns of the same days are inserted:

date,test, test, testx, testy ...
2022-09-01,demo1, demo2, demo3 ...
2022-09-02,demo4, demo5, demo6 ...

Any ideas?, thank you very much

Answers:

Try:

df["tmp"] = df.groupby("date").cumcount() + 1
out = df.pivot(index="date", columns="tmp", values="test").add_prefix("test_")
out.columns.name, out.index.name = None, None

print(out)

Prints:

           test_1 test_2 test_3
2022-09-01  demo1  demo2  demo3
2022-09-02  demo4  demo5  demo6
Answered By: Andrej Kesely
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.