以精度(如Decimal)将货币保存到pandas存储中

1 投票
1 回答
776 浏览
提问于 2025-04-30 01:37

在使用pandas处理货币时,我遇到了一些问题。之前我一直用默认的浮点数,但这种方式精度不够,容易出错,让我很烦恼。所以我想尝试用Decimal来处理一些数据,虽然这样计算可能会慢一些,但它的精度更高。不过,当我尝试把数据保存到pandas的存储中(比如通过pytables保存到hdf5格式)时,出现了这样的错误: TypeError: Cannot serialize the column [o] because its data contents are [mixed] object dtype

这是我想做的一个简单示例:

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保存到pandas的存储中?如果没有,是否有推荐的方式来精确存储货币数据?

我使用的是python 2.7.8,pandas 0.14.1,以及pytables 3.1.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

撰写回答