Python Pandas 添加前导零使所有月份都为2位数字

15

如何添加前导零以确保数字至少有两位。

     Week product  quantity        Month
0  201301    coke       1.5           1
1  201302   fanta       1.7           2
2  201304    coke       3.6           5
3  201306  sprite       2.4          10
4  201308   pepsi       2.9          12
即将上面的数据框转换为下面的形式:
     Week product  quantity         Month
0  201301    coke       1.5           01
1  201302   fanta       1.7           02
2  201304    coke       3.6           05
3  201306  sprite       2.4           10
4  201308   pepsi       2.9           12
3个回答

36

使用Series的map()方法和"{:02}".format

data = """     Week product  quantity        Month
0  201301    coke       1.5           1
1  201302   fanta       1.7           2
2  201304    coke       3.6           5
3  201306  sprite       2.4          10
4  201308   pepsi       2.9          12
"""

import pandas as pd
import io

df = pd.read_csv(io.BytesIO(data), delim_whitespace=True)
df["Month"] = df.Month.map("{:02}".format)

1
能否解释一下 .map("{:02}".format) 语法的原因?顺便说一句,这非常有帮助。 - addicted
请在出现错误时使用map("{:02d}".format)而不是map("{:02}".format)。 - Amit

6
在Python 2.7中,您可以使用以下方式格式化该值:
>>> month = 9
>>> '{:02}'.format(month)
'09'

这里的 {:02} 指将输入数字转换为2个字符,前面加上“0”。如果输入数字的长度为2,则该数字将保持不变。


看到你之前的问题,我建议 - df['MonthMax'] = '{:02}'.format(pd.DatetimeIndex(df['LastDayWeek']).month) - anuragal
抱歉,我的问题不够清晰,它涉及到一个Pandas数据框,我需要更新一列中的所有值。HYRY下面的解释用.map方法解决了这个问题。 - IcemanBerlin

0
在Python 2.7之前的版本中,存在printf风格的格式化方式:
>>> month = 9
>>> '%02d' % month
'09'

请参考参考资料以获取更多信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接