2015-09-04 157 views
1

我有一个熊猫的数据帧,看起来像这样的列(长得多,但这里的前几名行):回合大熊猫数据帧/系列

>df_fill['col1'] 

0  5987.8866699999998672865 
1  52215.5966699999989941716 
2  201.8966700000000003001 
3   3.8199999999999998401 

我想整列四舍五入到5位小数地方。我可以将它舍入到整数,但不是小数点后的数字。该列的类型是浮动的。

> np.around(df_fill['col1'], 0) 

0  5988 
1  52216 
2  202 
3   4 

> np.around(df_fill['col1'], 5) 

0  5987.8866699999998672865 
1  52215.5966699999989941716 
2  201.8966700000000003001 
3   3.8199999999999998401 

> (df_fill['col1']).round() 

0  5988 
1  52216 
2  202 
3   4 

>(df_fill['col1']).round(5) 

0  5987.8866699999998672865 
1  52215.5966699999989941716 
2  201.8966700000000003001 
3   3.8199999999999998401 

> (df_fill['col1']).round(decimals=5) 

0  5987.8866699999998672865 
1  52215.5966699999989941716 
2  201.8966700000000003001 
3   3.8199999999999998401 

> str((df_fill['col1']).round(decimals=5)) 
'0  5987.8866699999998672865\n1  52215.5966699999989941716\n2  201.8966700000000003001\n3   3.8199999999999998401\ 

我在这里错过了什么?

+0

不会'df_fill [ 'COL1']。轮(5)'只是工作? – EdChum

+0

什么是'df_fill ['col1']。dtype'? – unutbu

+0

@EdChum没有工作,试图在小数点后仍然得到19位数的结果。 – lilyrobin

回答

4

花车can only represent a subset of the real numbers。它只能精确地表示那些是两个负幂(“二进制分数”)之和的小数。 后您圆一个浮到5位,新的浮动未必是具有5个十进制数字,因为小数部分可能不如二进制小数究竟表达实数。相反,倒圆的回报最接近实数浮动。

如果已设置

pd.options.display.float_format = '{:.23g}'.format 

然后大熊猫最多可显示23个数字在彩车的字符串表示:

import pandas as pd 

pd.options.display.float_format = '{:.23g}'.format 

df_fill = pd.DataFrame({'col1':[ 5987.8866699999998672865, 52215.5966699999989941716, 
           201.8966700000000003001, 3.8199999999999998401]}) 

#      col1 
# 0 5987.8866699999998672865 
# 1 52215.596669999998994172 
# 2 201.89667000000000030013 
# 3 3.8199999999999998401279 

print(df_fill['col1'].round(5)) 
# 0 5987.8866699999998672865 
# 1 52215.596669999998994172 
# 2 201.89667000000000030013 
# 3 3.8199999999999998401279 
# Name: col1, dtype: float64 

但是,如果你的float_format设置为显示 5个十进制数字:

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

然后

print(df_fill['col1'].round(5)) 

产生

0 5987.88667 
1 52215.59667 
2  201.89667 
3  3.82000 
Name: col1, dtype: float64 

注底层浮子没有改变;只有它的显示方式。

+0

是啊,这是它。仍然有点困惑,但我确认了两行相等到第五位,然后不平等。对它们进行舍入,当它们仍然显示完整数字时,四舍五入的值是“相等的”。我改变了显示为5只为了缓解我的想法。谢谢! – lilyrobin

+0

在0.17.0中注释,也会有一个''DataFrame.round()''方法 – Jeff

1

你的问题是由于在代表浮点数精度问题。数字5987.88667不能完全用浮点数表示,可以表示的最接近的数字是5987.8866699999998672865。因此,您已经有数字最接近您想要在数组中的数字,并将其四舍五入到小数点后5位将不起作用。你已经拥有了正确的调用:

(df_fill['col1']).round(5) 

你可以看到,它的工作原理,如果你试图把为2位小数代替。所以我建议你不要担心。如果问题是数字是如何显示在屏幕上,那么你就可以打印数字的字符串进行正确的小数位数:

print "%.5f"%(df_fill['col1'])