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

Stu*_*ent 2 python string numpy dataframe pandas

目标:['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
Run Code Online (Sandbox Code Playgroud)

这会生成一个['Birth Month']不是我需要的值列表:

    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]
Run Code Online (Sandbox Code Playgroud)

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

    A   B   Birth Year  Birth Month
0   1   4   1912        04
1   2   5   1989        12
2   3   6   1921        09
Run Code Online (Sandbox Code Playgroud)

EdC*_*ica 6

将该系列的dtype转换为str使用astype并使用vectorised 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
Run Code Online (Sandbox Code Playgroud)

你所做的就是分配一个标量值(这就是为什么每一行都是相同的)并将元素转换为列表的str:

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

Out[217]:
'[3 6 9]'
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看分配结果:

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]'
Run Code Online (Sandbox Code Playgroud)