【问题标题】:How to add leading zero formatting to string in Pandas?如何在 Pandas 中为字符串添加前导零格式?
【发布时间】:2016-02-12 14:38:35
【问题描述】:

目标:用前导零格式化['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

【问题讨论】:

    标签: python string numpy pandas dataframe


    【解决方案1】:

    使用astype将系列的dtype转换为str,并使用矢量化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]'
    

    【讨论】:

    • EdChum - 使用您的代码我遇到了一个 AttributeError:'StringMethods' 对象没有属性 'zfill'。我正在使用 Python 2.7.10。
    • 你用的是什么版本的熊猫?
    • EdChum - 我将 pandas 更新到当前版本,您的解决方案运行良好。谢谢。
    猜你喜欢
    • 2014-07-13
    • 1970-01-01
    • 2017-08-12
    相关资源
    最近更新 更多