You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Pandas中如何仅去除数字字符串左侧一个前导零

解决方案

方法一:单独处理整数部分

直接拆分原始字符串的整数位和小数位,对整数位单独清理前导零,确保至少保留一个0,再拼接小数位。逻辑清晰易懂:

def format_pu(value):
    # 拆分整数部分(前2位)和小数部分(后8位)
    integer_part = value[:2]
    decimal_part = value[2:]
    # 清理整数部分前导零,若清理后为空则用"0"兜底
    cleaned_integer = integer_part.lstrip('0') or '0'
    return f"{cleaned_integer}.{decimal_part}"

# 应用到目标列
df_operacoes['PU Parte'] = df_operacoes['PU Parte'].map(format_pu)
df_operacoes['PU ContraParte'] = df_operacoes['PU ContraParte'].map(format_pu)

方法二:转数值类型自动格式化

利用数值类型特性,先将字符串转为整数,再除以10^8得到对应小数,最后格式化保留8位小数,自动处理前导零问题:

# 转整数→转小数→格式化保留8位小数
df_operacoes['PU Parte'] = df_operacoes['PU Parte'].astype(int).div(10**8).map(lambda x: f"{x:.8f}")
df_operacoes['PU ContraParte'] = df_operacoes['PU ContraParte'].astype(int).div(10**8).map(lambda x: f"{x:.8f}")

方法三:正则表达式替换

先拼接成带小数点的格式,再用正则匹配小数点前的冗余前导零,替换为单个0:

import re

# 拼接小数点格式
df_operacoes['PU Parte'] = df_operacoes['PU Parte'].map(lambda x: f'{x[:2]}.{x[2:]}')
# 替换小数点前的多个零为单个零
df_operacoes['PU Parte'] = df_operacoes['PU Parte'].str.replace(r'^0+(?=\.)', '0', regex=True)

# 对另一列执行相同操作
df_operacoes['PU ContraParte'] = df_operacoes['PU ContraParte'].map(lambda x: f'{x[:2]}.{x[2:]}')
df_operacoes['PU ContraParte'] = df_operacoes['PU ContraParte'].str.replace(r'^0+(?=\.)', '0', regex=True)

内容的提问来源于stack exchange,提问作者pedrosjo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 03:40:48