2015-09-04 158 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'])