pandas 四舍五入小数不起作用 [英] Pandas rounding decimals not working

查看:82
本文介绍了 pandas 四舍五入小数不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下发生了什么吗,还是我遗漏了一些非常明显的东西?

Can someone please explain what's happening me or am I missing something really obvious?

import pandas as pd
df = pd.DataFrame([[0.0094909865]])
df = df.round(9)
print(df)

这给了我 0.009490986.

我期望的是 0.009490987

有人能帮我理解吗?我正在使用 Pandas '0.20.3'

Can someone help me understand? I am using Pandas '0.20.3'

推荐答案

好问题.这是一个无证的怪癖.实际上,DataFrame.round 使用了 numpy.around.它应该在 pandas 文档 中提及.

Good question. This is an undocumented quirk. Actually, DataFrame.round uses numpy.around. It should be mentioned in pandas documentation.

numpy.around() 执行以下操作:

对于四舍五入的十进制值的中间值,Numpy四舍五入到最接近的偶数值.因此 1.5 和 2.5 舍入为 2.0,-0.5和 0.5 轮到 0.0 等

For values exactly halfway between rounded decimal values, Numpy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc.

请参阅参考了解更多详情.

from math import ceil, floor
import pandas as pd

df = pd.DataFrame([[0.0094909865]])

def float_round(num, places = 0, direction = floor):
    return direction(num * (10**places)) / float(10**places)

print( float_round(df.values,9,ceil) )
print( float_round(df.values,9) )

print( float_round(1.1389182804 ,9) )

结果

0.009490987
0.009490986

1.13891828

这篇关于 pandas 四舍五入小数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆