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

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

我查看了很多其他问题,但没有找到一个非常合适的问题。

假设我有数据框,df:

Name     Month
Bob      5
Jim      7
Mary     12

我正在尝试编写一个 for 循环,用一个数字为月份添加一个前导零(并按原样打印其他月份),然后我可以用列表覆盖该列。

这是我的

list={}
for i in df['Month']:
      if len(df['Month'][i]) < 2:
          print("{:02}".format(i))
      else:
          print(i)
print(list)
df['Month']=list

像这样的代码给我错误:

TypeError: object of type 'numpy.int64' has no len()

我不完全确定在哪里解决这个问题或从这里去哪里。谢谢!

给你(没有循环):

df["Month"] = df.Month.map("{:02}".format)
df['Month'].astype(str).str.zfill(2)

你可以试试这个:

df = pd.read_csv('file.csv', converters={'Month': '{:0>2}'.format}).astype('str')
print(df)

为此使用 zfill:

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

   Name Month
0   Bob    05
1   Jim    07
2  Mary    12