5

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!

gtomer
  • 5,643
  • 1
  • 10
  • 21
gf7
  • 145
  • 11
  • You're mixing 2 ways to do loops: - for i in df['Month'] will evaluate to 5, then 7, then 12. - probably you meant to do "for i in range(0, len(df['Month'] – trolloldem Sep 12 '20 at 15:28
  • Unfortunately I have to use a loop for this (it's for an assignment), so cannot use a workaround with zfill. Thank you trolloldem, I will look into changing that part. – gf7 Sep 12 '20 at 18:13

4 Answers4

5

Here you go (without loop):

df["Month"] = df.Month.map("{:02}".format)
gtomer
  • 5,643
  • 1
  • 10
  • 21
2

You can try this:

df = pd.read_csv('file.csv', converters={'Month': '{:0>2}'.format}).astype('str')
print(df)
Soumendra Mishra
  • 3,483
  • 1
  • 12
  • 38
1
df['Month'].astype(str).str.zfill(2)
Chris
  • 15,819
  • 3
  • 24
  • 37
1

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
NYC Coder
  • 7,424
  • 2
  • 11
  • 24