0

I have a panda DF as follows:

items_type     item_id    item_name    item_price
A              1          x            1.0
A              2          y            1.1
A              3          z            0.75
B              4          x            2.0
B              5          w            2.5
B              6          z            1.5
C              7          x            0.2
C              8          w            11.0
C              9          n            5.0

I need to create a new df , dropping item_id, and flatten item_name, as in:

items_type    x      y     z     w      n   
A             1.0    1.1   0.75  None   None
B             2.0    None  1.5   2.5    None
C             0.2    None  None  11.0   5.0

Please advise if there is a way to do via pivot or otherwise without have to loop

Thank

jscriptor
  • 775
  • 1
  • 11
  • 26
  • You can use `df.pivot`, documentation [here](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html) or you can use `df = df.set_index([items_type])['item_price'].unstack() \n df =df.reset_index()` –  Mar 25 '19 at 16:07
  • I tried pivot earlier, but I get a dataframe full of None. No errors, just a dataframe full of None. I tried your approach, but then I get an error: File "......pandas\core\reshape\reshape.py", line 107, in __init__ self.lift = 1 if -1 in self.index.labels[self.level] else 0 AttributeError: 'Index' object has no attribute 'labels' ... I have a large df. I am wondering if this could be the cause. – jscriptor Mar 25 '19 at 17:27
  • Could you post the `df` code here so that I can try it and get back to you? –  Mar 25 '19 at 17:29
  • I am working on a task myself and I recently had to pivot my df, which had about 1.2 million rows, and it worked. I really doubt it the size of your df is the cause here –  Mar 25 '19 at 17:31

0 Answers0