0

I have a data frame as shown below

df

cust_id         product
1               tv
1               phone
2               bat
2               ball
3               bat
4               ball
4               bat
4               tv
4               phone
5               tv
6               bat
7               bat
7               ball
7               tv
8               phone
8               tv

From the above I would like to prepare a data frame as shown below.

Expected output:

cust_id        0         1            2           3         
      1        tv        phone        NaN         NaN
      2        bat       ball         NaN         NaN
      3        bat       NaN          NaN         NaN
      4        ball      bat          tv          phone
      5        tv        NaN          NaN         NaN
      6        bat       NaN          NaN         NaN
      7        bat       ball         tv          NaN
      8        phone     tv           NaN         NaN

I tried below code but it created the list of items as one column

s = df.groupby(['cust_id'])['product'].apply(list)
Danish
  • 2,719
  • 17
  • 32
  • question 10 specifically – Mustafa Aydın Sep 05 '22 at 13:03
  • @MustafaAydın not exactly. Can you please add the answer here. – Danish Sep 05 '22 at 13:07
  • `df.assign(n=df.groupby("cust_id").cumcount()).pivot(index="cust_id", columns="n", values="product")` – Mustafa Aydın Sep 05 '22 at 13:11
  • @MustafaAydın Great, it worked perfectly. Thank you so much. If you wish you can add the answer and I will accept it. – Danish Sep 05 '22 at 13:16
  • 1
    uh, glad it works, but since question is closed as a duplicate, that's the preferred way (and i can't answer anyway :)), but thanks. (btw, above, different from the linked Q&A is i `assign` instead of `insert`ing to not affect `df`; but flow is the same) – Mustafa Aydın Sep 05 '22 at 13:17

0 Answers0