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

在R中为小数点前不足3位的数字补前导零

解决方案

可以通过 pandas 的字符串处理方法拆分数字的整数与小数部分,对整数部分补前导零后再合并,具体步骤如下:

1. 构建示例数据

首先还原你的原始 DataFrame:

import pandas as pd

data = {
    'id': ['A', 'B', 'C', 'E', 'F', 'G', 'F'],
    'col1': [8, 125.4, 27.1, 2998, 12341, 7.2, 6.52]
}
df = pd.DataFrame(data)

2. 处理生成目标列 col2

核心逻辑是拆分数字的整数和小数部分,对整数部分用 zfill(3) 补前导零(长度≥3时保持原样),再合并两部分:

# 将数字转为字符串,避免浮点数格式问题
df['col1_str'] = df['col1'].astype(str)
# 拆分整数与小数部分,生成两列
split_cols = df['col1_str'].str.split('.', expand=True)
split_cols.columns = ['int_part', 'dec_part']
# 整数部分补前导零至3位,长度超过3则不变
split_cols['int_part'] = split_cols['int_part'].str.zfill(3)
# 合并整数与小数部分:存在小数则拼接,否则仅保留整数部分
df['col2'] = split_cols.apply(
    lambda x: f"{x['int_part']}.{x['dec_part']}" if pd.notna(x['dec_part']) else x['int_part'],
    axis=1
)
# 清理中间辅助列
df = df.drop('col1_str', axis=1)

3. 输出结果

执行上述代码后,df 的内容与你期望的输出一致:

id    col1      col2
0  A     8.0       008
1  B   125.4     125.4
2  C    27.1     027.1
3  E  2998.0      2998
4  F  12341.0     12341
5  G     7.2     007.2
6  F     6.52    006.52

注:如果你的 col1 原本就是字符串类型,可以跳过转字符串的步骤,直接拆分处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:15:26