python pandas 添加前导零以使所有月份均为 2 位数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20990863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:31:32  来源:igfitidea点击:

python pandas add leading zero to make all months 2 digits

pythonpandasdataframe

提问by IcemanBerlin

How can I add a leading zero so i have a minimum of double digits.

如何添加前导零,以便我至少有两位数。

     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

i.e convert the above dataframe to be the below:

即将上面的数据框转换为下面的:

     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

回答by HYRY

use map()method of Series with "{:02}".format:

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)

回答by anuragal

In Python 2.7 you can format this value using

在 Python 2.7 中,您可以使用

>>> month = 9
>>> '{:02}'.format(month)
'09'

here 2 in {:02} specifies convert the input digit in 2 chars by prefixing '0'. If input digit is of length 2 then that digit will remain unchanged.

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

回答by pts

In Python versions earlier than 2.7, there is printf-style formatting:

在 2.7 之前的 Python 版本中,有 printf 样式的格式:

>>> month = 9
>>> '%02d' % month
'09'

See the referencefor more information.

有关更多信息,请参阅参考资料