How to change format of a string in a column to 3 digits "000" in Python

Viewed 76

I have two columns: one is called "Style" and the other is called "Color". I would like to create a column called "Product_Code" concatenating Style then Color. The Color column should contain three digits but the column contains floats and some rows contain two digits since the leading "0" isn't present. Here's an example of what I'd like:

   Product_Code   Style   Color   Price
0       323-010     323      10      10
1       400-111     400     111       8
2       323-023     323      23       5
1 Answers

You can use zfill to fill left zeros and string concatenation:

df['Product_Code'] = df.Style.astype(str) + '-' + df.Color.astype(str).str.zfill(3)
Related