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!
Here you go (without loop):
df["Month"] = df.Month.map("{:02}".format)
You can try this:
df = pd.read_csv('file.csv', converters={'Month': '{:0>2}'.format}).astype('str')
print(df)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With