Python pandas add leading zero so that all months are 2 digits

How can I add a leading zero, so I have a minimum of two-digit numbers.

     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 data frame as 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
+4
source share
3 answers

use map()series method 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)
+8
source

In Python 2.7, you can format this value with

>>> month = 9
>>> '{:02}'.format(month)
'09'

here 2 in {: 02} indicates the conversion of the input digit into 2 characters by the prefix '0'. If the input digit has a length of 2, then this digit will remain unchanged.

+3
source

Python 2.7 printf:

>>> month = 9
>>> '%02d' % month
'09'

. .

0

All Articles