How can I spilt element to different columns in python?

Viewed 64

I am working on a python program to output a dataset of ranking of some items.

This is my code:

import pandas as pd

list=[{'ranking': 1, 'sku': 'WD-0215', 'name': 'Sofa', 'price': '$1,299.00', 'detail': 'Red'}, 
      {'ranking': 1, 'sku': 'WD-0215', 'name': 'Sofa', 'price': '$1,299.00', 'detail': 'Cottom'},
      {'ranking': 1, 'sku': 'WD-0215', 'name': 'Sofa', 'price': '$1,299.00', 'detail': 'Wood Lab'},
      {'ranking': 2, 'sku': 'sfr20', 'name': 'TV', 'price': '$1,861.00 – $3,699.00', 'detail': 'W1360×D750×H710'},
      {'ranking': 2, 'sku': 'sfr20', 'name': 'TV', 'price': '$1,861.00 – $3,699.00', 'detail': 'LED'}, 
      {'ranking': 2, 'sku': 'sfr20', 'name': 'TV', 'price': '$1,861.00 – $3,699.00', 'detail': 'Made in Japan'},
      {'ranking': 2, 'sku': 'sfr20', 'name': 'TV', 'price': '$1,861.00 – $3,699.00', 'detail': 'Nordic'}
     ]

df = pd.DataFrame(list)
print(df)
df.to_csv('item.csv',encoding='utf_8_sig')

However my expected output should be like this:

ranking sku name price detail1 detail2 detail3 detail4
1 WD-0215 Sofa $1299.00 Red Cottom Wood Lab none
1 sfr20 TV $1861.00-$3699.00 W1360×D750×H710 LED Made in Japan Nordic

How can change the code to ouput this result?

1 Answers

Use GroupBy.cumcount for counter and reshape by Series.unstack:

g = df.groupby(['ranking', 'sku', 'name', 'price']).cumcount().add(1)

df = df.set_index(['ranking', 'sku', 'name', 'price', g])['detail'].unstack().add_prefix('detail')
print (df)
                                                    detail1 detail2  \
ranking sku     name price                                            
1       WD-0215 Sofa $1,299.00                          Red  Cottom   
2       sfr20   TV   $1,861.00 – $3,699.00  W1360×D750×H710     LED   

                                                  detail3 detail4  
ranking sku     name price                                         
1       WD-0215 Sofa $1,299.00                   Wood Lab     NaN  
2       sfr20   TV   $1,861.00 – $3,699.00  Made in Japan  Nordic  
Related