【问题标题】:Remove leading zeroes in pandas column but only for numeric删除 pandas 列中的前导零,但仅适用于数字
【发布时间】:2022-06-30 20:48:43
【问题描述】:

我的 pandas 数据框如下所示:

col1 col2
1 ABC8392akl
2 001523
3 000ABC58

现在我想删除前导零,如果字符串只是数字的话。有什么建议么? 所以结果应该是:

col1 col2
1 ABC8392akl
2 1523
3 000ABC58

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以为此使用带有str.replace 的正则表达式:

    df['col2'] = df['col2'].str.replace('^0+(?!.*\D)', '', regex=True)
    

    输出:

       col1        col2
    0     1  ABC8392akl
    1     2        1523
    2     3    000ABC58
    

    正则表达式:

    ^0+       # match leading zeros
    (?!.*\D)  # only if not followed at some point by a non digit character
    

    【讨论】:

      【解决方案2】:

      使用

      where = (df['col2'].str.isdigit(), 'col2')
      df.loc[where] = df.loc[where].str.lstrip('0')
      

      【讨论】:

      • 哈哈,我正准备用与变体类似的方法来更新我的答案;)
      猜你喜欢
      • 2014-09-16
      • 2014-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多