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

使用np.around保留指定位数小数的问题及解决方法

能否使用np.around实现保留n位小数的四舍五入操作?

示例验证

创建测试用的pandas DataFrame

先构造包含测试数值的DataFrame,用来对比不同方法的四舍五入结果:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'num':  [0.444, 0.445, 0.446, 0.4, 0.41, 0.49],
    'near': [0.44, 0.45, 0.45, 0.4, 0.41, 0.49]
})

df
# 输出结果:
#      num  near
# 0  0.444  0.44
# 1  0.445  0.45
# 2  0.446  0.45
# 3  0.400  0.40
# 4  0.410  0.41
# 5  0.490  0.49

np.around - 不符合预期

直接使用np.around处理DataFrame列时,部分结果不符合常规四舍五入预期:

np.around(df['num'], 2)    
# 输出结果:
# 0    0.44
# 1    0.44  # 不符合预期,常规四舍五入应为0.45
# 2    0.45
# 3    0.40
# 4    0.41
# 5    0.49
# Name: num, dtype: float64

内置round函数处理单个数值 - 符合预期

用Python内置的round函数处理单个数值时,结果符合常规四舍五入逻辑:

round(0.445, 2)

# 输出结果:0.45  # 符合预期

内置round函数处理整列 - 不符合预期

直接对DataFrame列使用内置round函数,结果和np.around一致,仍存在不符合预期的情况:

round(df['num'], 2)

# 输出结果:
# 0    0.44
# 1    0.44  # 不符合预期
# 2    0.45
# 3    0.40
# 4    0.41
# 5    0.49
# Name: num, dtype: float64

通过lambda对列中每个元素应用内置round函数 - 符合预期

通过apply结合lambda表达式,对列中每个元素单独应用内置round函数,结果完全符合常规四舍五入预期:

df['num'].apply(lambda x: round(x, 2))

# 输出结果:
# 0    0.44
# 1    0.45  # 符合预期
# 2    0.45
# 3    0.40
# 4    0.41
# 5    0.49
# Name: num, dtype: float64

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:40:36