简体   繁体   English

在 Python 中使用 for 循环向日期列添加前导零

[英]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:假设我有数据框,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.我正在尝试编写一个 for 循环,它将用一位数向月份添加前导零(并按原样打印其他月份),然后我可以用列表覆盖该列。

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!谢谢!

给你(没有循环):

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)
df['Month'].astype(str).str.zfill(2)

Use zfill for this:为此使用 zfill:

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

   Name Month
0   Bob    05
1   Jim    07
2  Mary    12

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM