How to add leading zeros in a month columns in Pandas?

Question:

I looked through a lot of other questions but didn’t see one that quite fit.

Say I have the dataframe, df:

Name     Month
Bob      5
Jim      7
Mary     12

I’m trying to write a for loop that would add a leading zero to the months with a single digit (and just print the other months as is), and then I can overwrite the column with the list.

Here’s what I have

list={}
for i in df['Month']:
      if len(df['Month'][i]) < 2:
          print("{:02}".format(i))
      else:
          print(i)
print(list)
df['Month']=list

The code just like this is giving me the error:

TypeError: object of type 'numpy.int64' has no len()

I’m not entirely sure where to troubleshoot that or where to go from here. Thank you!

Asked By: gf7

||

Answers:

Here you go (without loop):

df["Month"] = df.Month.map("{:02}".format)
Answered By: gtomer
df['Month'].astype(str).str.zfill(2)
Answered By: Chris

You can try this:

df = pd.read_csv('file.csv', converters={'Month': '{:0>2}'.format}).astype('str')
print(df)
Answered By: Soumendra Mishra

Use zfill for this:

df['Month'] = df['Month'].astype(str).str.zfill(2)
print(df)

   Name Month
0   Bob    05
1   Jim    07
2  Mary    12
Answered By: NYC Coder