0

Hi I have a dataset as below stored as pandas data frame (df)

device_id  domain    date      event  product_label     event   Product_label1
   11      Amazon  24112017    basket                   view        TV
   12      Tesco   30122017    basket                   view        Coffe
   15      Costco  20092018    basket                   view        Clothes 

I tried using the panda's stack function df.stack() which doesn't render the right format

Below is the format I want to reshape the data as,

device_id  domain    date      event  product_label     
   11      Amazon  24112017    basket
   11      Amazon  24112017    view     TV   
   12      Tesco   30122017    basket
   12      Tesco   30122017    view     Coffe

Referred to the below stack-overflow as well doesn't work for the above problem Python Pandas Wide to Long Format Change with Column Titles Spliting

EricA
  • 403
  • 2
  • 14
  • Is the bottom an example of what you want or the output of `stack()`? – Jab Nov 08 '18 at 10:42
  • @Jaba, The output of stack() function is not attached, I have edited the question to make it clear, Thanks – EricA Nov 08 '18 at 10:48
  • Thanks, much easier to tell now. I'm not familiar with pandas but I can attempt to research it – Jab Nov 08 '18 at 10:54
  • May be best to have 2 tables imo as you're creating duplicate `device_id`'s and this seems like bad practice. I'd go with a `devices` dataframe and an `events` one. Just my 2 cents – Jab Nov 08 '18 at 10:57
  • I think that would just complex the code since the table I am trying to format is combined using multiple tables. – EricA Nov 08 '18 at 11:00
  • Use `df.melt(id_vars=['device_id','domain','date','Product_label1'], value_vars='event', value_name='event')` – Abhi Nov 08 '18 at 11:40

1 Answers1

0

You may be looking for melt() as described in this question. Check to make sure I'm correct. I don't deal with pandas much.

df.melt(
    id_vars=['devide_id', 'domain'],
    value_vars=['event', 'product_label', 'product_label1']
)
Jab
  • 26,853
  • 21
  • 75
  • 114
  • Please let me know if I made a mistake I'll edit, or if I'm wrong I'll delete. Hope this helps! – Jab Nov 08 '18 at 11:21