How can I add a leading zero so i have a minimum of double digits.
Week product quantity Month
0 201301 coke 1.5 1
1 201302 fanta 1.7 2
2 201304 coke 3.6 5
3 201306 sprite 2.4 10
4 201308 pepsi 2.9 12
i.e convert the above dataframe to be the below:
Week product quantity Month
0 201301 coke 1.5 01
1 201302 fanta 1.7 02
2 201304 coke 3.6 05
3 201306 sprite 2.4 10
4 201308 pepsi 2.9 12
Pandas zfill() method is used to fill left side of string with zeros. If length of string is more than or equal to the width parameter, then no zeroes are prefixed. Since this is a string method, it is only applicable on series of strings and . str has to be prefixed every time before calling this method.
use map()
method of Series with "{:02}".format
:
data = """ Week product quantity Month
0 201301 coke 1.5 1
1 201302 fanta 1.7 2
2 201304 coke 3.6 5
3 201306 sprite 2.4 10
4 201308 pepsi 2.9 12
"""
import pandas as pd
import io
df = pd.read_csv(io.BytesIO(data), delim_whitespace=True)
df["Month"] = df.Month.map("{:02}".format)
In Python 2.7 you can format this value using
>>> month = 9
>>> '{:02}'.format(month)
'09'
here 2 in {:02} specifies convert the input digit in 2 chars by prefixing '0'. If input digit is of length 2 then that digit will remain unchanged.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With