pandas 在 numpy 中舍入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42813777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rounding in numpy?
提问by user7715674
I have strange problem with python pandas and numpy.
我对 python pandas 和 numpy 有奇怪的问题。
>>> np.float64(1) * np.float64(85000) * np.float64(7.543709)
641215.26500000001
>>> round( np.float64(1) * np.float64(85000) * np.float64(7.543709), 2 )
641215.26000000001
>>> np.round( np.float64(1) * np.float64(85000) * np.float64(7.543709), 2 )
641215.26000000001
How to round to get correct result 641215.27?
如何四舍五入以获得正确的结果 641215.27?
回答by Morgoth
Numpy's round method favours even numbers, have a look at the abridged numpy source code:
Numpy 的 round 方法偏向于偶数,看一下删节的 numpy 源代码:
def round_(a, decimals=0, out=None):
return around(a, decimals=decimals, out=out)
def around(a, decimals=0, out=None):
"""
Evenly round to the given number of decimals.
Notes
-----
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. Results may also be surprising due
to the inexact representation of decimal fractions in the IEEE
floating point standard [1]_ and errors introduced when scaling
by powers of ten.
Examples
--------
>>> np.around([0.37, 1.64])
array([ 0., 2.])
>>> np.around([0.37, 1.64], decimals=1)
array([ 0.4, 1.6])
>>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
array([ 0., 2., 2., 4., 4.])
>>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
array([ 1, 2, 3, 11])
>>> np.around([1,2,3,11], decimals=-1)
array([ 0, 0, 0, 10])
"""
Example:
例子:
If you need to print the string you can format it to give you the right answer:
如果您需要打印字符串,您可以格式化它以获得正确的答案:
import numpy as np
num = np.float64(1) * np.float64(85000) * np.float64(7.543709)
print(num)
print(float("{0:.2f}".format(num)))
print(np.round(num, 2))
print()
num += 0.02
print(num)
print(float("{0:.2f}".format(num)))
print(np.round(num, 2))
gives you
给你
641215.265
641215.27
641215.26
641215.285
641215.29
641215.28
回答by user7715674
Yes, but you can't use round( float(num), 2 )
when you work with dataframes:
是的,但是在使用round( float(num), 2 )
数据框时不能使用:
for examle: df.first * df.second * df.third
How to round in that case?
You can't make float(dt.first)
?
例如:df.first * df.second * df.third
在这种情况下如何舍入?你做不到float(dt.first)
?
This is one solution: df.first.apply(lambda x: round(float(x), 2))
But I think is not fast...
这是一种解决方案:df.first.apply(lambda x: round(float(x), 2))
但我认为并不快......