簡體   English   中英

python/pandas 保持與字符串完全一樣的小數位

[英]python/pandas keeping decimal places exactly as in string

我是 Python/pandas 的新手,我有一個小數問題,幾個小時已經想不通如何解決它。 基本上我想將 CSV 文件讀入 Pandas 並保持小數點與文本中存儲的完全一樣,以便將來進行比較和簡單的數學運算。 例子:

is_string_dtype(report['item_weight_kg'])
Out[12]: True

l = report.loc[report['item'] == 'B0WY']
num1 = l['item_weight_kg'][8210]

num1
Out[14]: '22.000370049504'

然后我嘗試將它們轉換為浮點數,這給了我一個以...3999而不是...4結尾的值

report['item_weight_kg'] = report.apply(lambda x: float(x['item_weight_kg']), axis = 1 )

l = report.loc[report['item'] == 'B0WY']
num1 = l['item_weight_kg'][8210]

num1
Out[17]: 22.000370049503999

導入數據集后,我嘗試將其轉換為浮點數,並在控制台中正常工作,返回所需的值,但是當我嘗試將其應用於整個數據集時,它沒有

float(decimal.Decimal(l['item_weight_kg'][8210]))
Out[23]: 22.000370049504

report['item_weight_kg'] = report.apply(lambda x: float(decimal.Decimal(x['item_weight_kg'])), axis = 1 )    
l = report.loc[report['item'] == 'B0WY']
num1 = l['item_weight_kg'][8210]

num1
Out[25]: 22.000370049503999

如何解決這個問題?

通常我會為字符串或圓形函數使用打印格式。

https://docs.python.org/3/library/functions.html?highlight=round#round

因為您使用的是十進制,所以您可能會通過更改精度來滿足您的要求

https://docs.python.org/3/library/decimal.html?highlight=round

我有一些好消息和壞消息要告訴你。
壞消息是在 python 中:
0.1 + 0.2會給你0.30000000000000004
0.1 + 0.2 == 0.3會給出False
這不僅僅是在python中。 這種現象發生在非常多的編程語言中。 事實上,有一個專門針對它的網站! : https://0.30000000000000004.com/
您可以在此處的官方 Python 文檔中閱讀有關此內容的更多信息。
問題是,處理浮點數很棘手,尤其是當您嘗試像您的情況一樣進行精確的數學運算(即相等)時。
處理浮點數時永遠不要指望精確的數學!
相反,當您嘗試檢查浮動是否相等時,您會檢查它們是否彼此非常接近 Python 3.5+ 提供了這個功能( 見這里),你可以自己實現一個。
一個簡單的浮點相等比較是這樣的:

epsilon = 0.0000001 # the smallest acceptable precision error
def float_equals(a,b):
    return abs(a-b) <= epsilon

但是如果我們想要比標准 python 提供的精度更高的精度怎么辦?
在這種情況下,您可以使用任意精度的庫,例如mpmath 這是個好消息(也許,idk)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM