代码之家  ›  专栏  ›  技术社区  ›  Umar.H

根据长度将尾部0添加到df.列中的字符串

  •  2
  • Umar.H  · 技术社区  · 6 年前

    寻找一种应用于df的链式方法。

    考虑以下DF。

    Store
    1
    33
    455
    

    我要做的是确定长度并根据长度附加一个0。

    for s in df.Store:
      if s.str.len() == 3:
        "0" + s
    

    但是这不起作用。

    if df.Store == df[df['Store'].str.len() == 1]:
        "0" + df.Store
    

    但两者都不起作用,只返回一个空白输出。

    我正在处理一个对象数据类型。

    期望输出:

    Store
    0001
    0033
    0455
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Joe    6 年前

    使用此选项:

    df['Store'] = df['Store'].apply(lambda x: x.zfill(4))
    
        2
  •  2
  •   jezrael    6 年前

    使用 Series.str.zfill .

    0 值按字符串的最大长度是可能的计数长度 Series.str.len max :

    df['Store'] = df['Store'].astype(str)
    df['Store'] = df['Store'].str.zfill(df['Store'].str.len().max())
    print (df)
      Store
    0   001
    1   033
    2   455
    

    按标量:

    df['Store'] = df['Store'].astype(str).str.zfill(4)
    print (df)
      Store
    0  0001
    1  0033
    2  0455