Search code examples
python-3.xpandasdataframedata-analysis

Pandas Pivot table without aggregating


I have a dataframe df as:

Acct_Id  Acct_Nm   Srvc_Id   Phone_Nm   Phone_plan_value   Srvc_Num
51       Roger     789       Pixel      30                 1
51       Roger     800       iPhone     25                 2
51       Roger     945       Galaxy     40                 3
78       Anjay     100       Nokia      50                 1
78       Anjay     120       Oppo       30                 2
32       Rafa      456       HTC        35                 1

I want to transform the dataframe so I can have 1 row per Acct_Id and Acct_Nm as:

    Acct_Id   Acct_Nm    Srvc_Num_1                             Srvc_Num_2                              Srvc_Num_3
                         Srvc_Id   Phone_Nm   Phone_plan_value  Srvc_Id   Phone_Nm   Phone_plan_value   Srvc_Id   Phone_Nm   Phone_plan_value
          51  Roger      789       Pixel      30                800       iPhone     25                 945       Galaxy     40
          78  Anjay      100       Nokia      50                120       Oppo       30
          32  Rafa       456       HTC        35

I am not sure how to achieve the same in pandas.


Solution

  • How about:

    df.set_index(['Acct_Id', 'Acct_Nm', 'Srvc_Num']).unstack().swaplevel(0, 1, axis = 1).sort_index(axis = 1)