如何在Pandas中给字符串添加前导零格式?

6

目标:['Birth Month']格式化为带前导零的形式。

目前,我的代码如下:

import pandas as pd
import numpy as np

df1=pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])])
df1['Birth Year']= np.random.randint(1905,1995, len(df1))
df1['Birth Month']= str(np.random.randint(1,12, len(df1))).zfill(2)
df1

这会生成一个值列表['出生月份'],但这不是我需要的:

    A   B   Birth Year  Birth Month
0   1   4   1912        [4 5 9]
1   2   5   1989        [4 5 9]
2   3   6   1921        [4 5 9]

相反,我正在寻找像以下这样在['Birth Month']中的值和格式:

    A   B   Birth Year  Birth Month
0   1   4   1912        04
1   2   5   1989        12
2   3   6   1921        09
1个回答

10
将序列的dtype转换为str,使用astype函数,并使用向量化的str.zfill函数填充0
In [212]:
df1=pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])])
df1['Birth Year']= np.random.randint(1905,1995, len(df1))
df1['Birth Month']= pd.Series(np.random.randint(1,12, len(df1))).astype(str).str.zfill(2)
df1

Out[212]:
   A  B  Birth Year Birth Month
0  1  4        1940          09
1  2  5        1945          04
2  3  6        1962          03

你所做的只是给一个标量赋值(这就是每一行都相同的原因),并将元素转换为列表的 str:

In [217]:
df1['Birth Month'].iloc[0]

Out[217]:
'[3 6 9]'

您可以在此处查看分解的任务结果:
In [213]:
(np.random.randint(1,12, len(df1)))

Out[213]:
array([5, 7, 4])

In [214]:
str(np.random.randint(1,12, len(df1))).zfill(2)

Out[214]:
'[2 9 5]'

1
EdChum - 使用你的代码时,我遇到了一个 AttributeError: 'StringMethods' 对象没有 'zfill' 属性的错误。我正在使用 Python 2.7.10。 - Student
你使用的pandas版本是多少? - EdChum
EdChum - 我已将pandas更新到最新版本,你的解决方案完美地运行了。谢谢。 - Student

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