2014-10-28 40 views
0

在熊猫中,我使用货币工作了很多。到目前为止,我一直在使用默认的浮点数,但处理精度不足的问题令人讨厌并且容易出错。我试图切换到使用Decimal来处理某些部分,虽然它可能会使计算速度变慢很多,但确实如此。然而,当我尝试保存到一个大熊猫存储(例如hdf5store通过pytables)我得到: TypeError: Cannot serialize the column [o] because its data contents are [mixed] object dtype以精确的方式将货币保存到熊猫商店(如Decimal?)

这里是我想要做一个简短的样本:

import pandas as pd 
from decimal import Decimal 
teststore = pd.HDFStore('teststore.h5') 
df = pd.DataFrame(data={'o':[Decimal('5.1')]}) 
teststore['test'] = df 

..这提高了上面的例外。 df.convert_objects(convert_numeric=True)没有帮助。

有没有办法将Decimal保存到熊猫商店,如果不是,有没有一种推荐的方式来精确地将货币存储在熊猫商店中?

我使用python 2.7.8,pandas 0.14.1和pytables 3.1.1。

回答

1

适用于0.15.0。尽管它基本上是作为一个实际的python对象进行腌制的,所以使用HDF5几乎没有任何好处。

In [46]: from decimal import Decimal 

In [47]: teststore = pd.HDFStore('teststore.h5') 

In [48]: df = pd.DataFrame(data={'o':[Decimal('5.1')]}) 

In [49]: teststore['test'] = df 
pandas/io/pytables.py:2487: PerformanceWarning: 
your performance may suffer as PyTables will pickle object types that it cannot 
map directly to c-types [inferred_type->mixed,key->block0_values] [items->['o']] 

    warnings.warn(ws, PerformanceWarning) 

作为一个仅供参考,一般float64有14-16位的精度,所以不知道你为什么不使用它们(您可能需要更改显示打印精度看到它)。

In [50]: In [34]: pd.set_option('precision',16) 

In [51]: In [35]: s = Series([0.0000000000001,0.000000000000002]) 

In [52]: s+s 
Out[52]: 
0 0.000000000000200 
1 0.000000000000004 
dtype: float64 
+0

非常酷,它工作在0.15.0和性能警告注意。 – fantabolous 2014-10-29 04:09:18

+0

re np.float64 vs decimal:我不需要这样的精度水平 - 通常最多我需要低至0.0001。例如,如果我从0开始并加1分(0.01)十次,结果为10美分(0.1),则结果与直接指定0.1不同。我最终不得不建造和使用一个小型的“软”比较器等库,这些库允许少量的错误,这些错误比较慢并且使用起来很麻烦。在SO和其他地方有很多关于这个的线索,推荐的解决方案通常似乎是Decimal,尽管我没有发现任何特定的numpy/pandas。 – fantabolous 2014-10-29 04:21:00