Search code examples
pythonpandasfor-loopleading-zero

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


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!


Solution

  • Here you go (without loop):

    df["Month"] = df.Month.map("{:02}".format)