Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas add leading zero to make all months 2 digits

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
like image 985
IcemanBerlin Avatar asked Jan 08 '14 08:01

IcemanBerlin


People also ask

How do you fill leading zeros in Pandas?

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.


2 Answers

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)
like image 188
HYRY Avatar answered Sep 22 '22 09:09

HYRY


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.

like image 28
anuragal Avatar answered Sep 22 '22 09:09

anuragal