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

如何移除DataFrame列中数值末尾的最后一个0?

解决方法:移除DataFrame列值末尾的最后一个0

针对你的需求,分两种数据类型场景给出解决方案:

场景1:列数据为数值类型(float)

如果col1是数值类型,可通过格式化字符串将数值转为保留两位小数的格式,自动去除末尾多余的0:

import pandas as pd

# 构造示例DataFrame
df = pd.DataFrame({'col1': [0.100, 0.200, 0.300, 0.400, 0.500]})

# 格式化处理为两位小数的字符串
df['col1'] = df['col1'].apply(lambda x: f"{x:.2f}")

处理后col1的值会变为0.10、0.20这类字符串形式。如果仅需调整显示效果、不改变实际存储的数值,可设置pandas显示选项:

pd.options.display.float_format = '{:.2f}'.format

场景2:列数据为字符串类型

如果col1是字符串类型(如值为"0.100"),直接截取字符串的前n-1位即可去掉最后一个0:

import pandas as pd

df = pd.DataFrame({'col1': ["0.100", "0.200", "0.300", "0.400", "0.500"]})

# 移除最后一个字符
df['col1'] = df['col1'].str[:-1]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:35:21