1

I have dataframe below where i trying to get all products that out in the same order in one single line.

I using the code and dataframe below.

df3 = df1.groupby(df1.index)['PartNo'].agg([('product','first'), ('productNew','last')])
        Product 
88      prod1
88      prod2
88      prod3
89      prod3
89      prod4

However, the max that I can get is 2 products based in 'first' and 'last' agg.

My output is.

        product  productNew     
88      prod1  prod2
89      prod3  prod4

How i can change my code to get N products in the same line for each order as sample below?

        0       1       2.....N 
88      prod1  prod2 prod3
89      prod3  prod4 NaN
Caio Euzébio
  • 127
  • 1
  • 1
  • 10

1 Answers1

0

This is pivot with index:

(df.assign(col=df.groupby(level=0).PartNo.cumcount())
  .pivot(columns='col', values='PartNo'))

Output:

col      0      1      2
88   prod1  prod2  prod3
89   prod3  prod4    NaN
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
  • its returning me the error message. ```--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) AttributeError: 'DataFrameGroupBy' object has no attribute 'PartNo'``` – Caio Euzébio Nov 01 '19 at 16:13
  • `Product` or `PartNo`? Your code says `PartNo`, but your data says `Product` – Quang Hoang Nov 01 '19 at 16:15
  • Code corrected and data frame also. bur the error correct is ```PartNo```. The error is ```----> 3 df3 = df1.assign(col=df1.groupby(level=0).PartNo.cumcount()).PartNo(columns='col', values='PartNo') TypeError: 'Series' object is not callable``` i using pandas ``0.24`` – Caio Euzébio Nov 01 '19 at 16:18
  • `df1.assign(..).PartNo`? isn't it `df1.assign(...).pivot(...)`? – Quang Hoang Nov 01 '19 at 16:20