Search code examples
pythonpandaspivotpivot-table

Desnormalize a table with python


I'm confused when i have to desnormalize a table with pandas For example, i have this table:

enter image description here

And I would like to desnormalize and receive something like that:

enter image description here

I'd appreciate your help


Solution

  • Try:

    df["tmp"] = df.groupby("Idn")["Idn"].transform("cumcount") + 1
    
    x = df.pivot(index="Idn", columns="tmp")
    x.columns = [f"{name}{c}" for name, c in x.columns]
    print(x.reset_index())
    

    Prints:

        Idn  test_m1  test_m2  test_m3       date1       date2       date3  test_p1  test_p2  test_p3
    0  4393        1        7        4  2010-12-19  2019-05-24  2012-04-16        8        2       10