Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python pandas how increase +1 end of each sku?

I have an pandas dataframe like this:

   product name             color                 sku
   
Men regular T-Shirt    White, Black, Orange      #VDY45P
Men  T-Shirt            Black, Orange            #VFY55P

my expected result will be like this:

Basically I want to add +1 end of my sku for related product.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 product name             color                 sku
   
Men regular T-Shirt    White                 #VDY45P-01
Men regular T-Shirt    Black                 #VDY45P-02
Men regular T-Shirt    Orange                #VDY45P-03 
Men  T-Shirt           Black                 #VFY55P-01
Men  T-Shirt           Orange                #VFY55P-02

>Solution :

explode the column, and add the cumcount value per group:

(df
 .assign(color=lambda d: d['color'].str.split(',\s*'))
 .explode('color')
 .assign(sku=lambda d: d['sku']+'-'+d.groupby(level=0) 
                                     .cumcount().add(1)
                                     .astype(str).str.zfill(2))
)

Output:

          product name   color         sku
0  Men regular T-Shirt   White  #VDY45P-01
0  Men regular T-Shirt   Black  #VDY45P-02
0  Men regular T-Shirt  Orange  #VDY45P-03
1          Men T-Shirt   Black  #VFY55P-01
1          Men T-Shirt  Orange  #VFY55P-02
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading