Home > Enterprise >  Pandas dataframe rows merge by date in a single row
Pandas dataframe rows merge by date in a single row

Time:10-10

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

CodePudding user response:

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
  • Related