繁体   English   中英

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

[英]How to add leading zero formatting to string in 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

它在['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]

相反,我在['Birth Month']寻找类似于以下内容的值和格式:

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

使用astype将系列的astypestr并使用矢量化的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]'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM