Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using for loop in Python to add leading zeros to date column

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!

like image 441
gf7 Avatar asked Sep 12 '20 15:09

gf7


Video Answer


2 Answers

Here you go (without loop):

df["Month"] = df.Month.map("{:02}".format)
like image 103
gtomer Avatar answered Nov 14 '22 23:11

gtomer


You can try this:

df = pd.read_csv('file.csv', converters={'Month': '{:0>2}'.format}).astype('str')
print(df)
like image 37
Soumendra Mishra Avatar answered Nov 14 '22 23:11

Soumendra Mishra