Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 960
June Smith Avatar asked Jan 23 '26 21:01

June Smith


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)
like image 80
Quang Hoang Avatar answered Jan 25 '26 11:01

Quang Hoang