什么 dtype 用于 pandas 数据框中的货币表示? [英] What dtype to use for money representation in pandas dataframe?
问题描述
所以我有一个 Pandas 数据框对象,其中有两个小数位精度的货币列,例如133.04".没有三位或三位以上小数的数字,只有两位.
So I have a pandas dataframe object with column for money with two decimal places precision like "133.04". There are no numbers with 3 or more decimal places, only two.
我尝试为此使用 Decimal 模块,但是当我尝试像这样重新采样时
I've tried to use Decimal module for this, but when I tried to re-sample it like this
gr_by_price = df['price'].resample(timeframe, how='ohlc')
我明白
pandas.core.groupby.DataError: No numeric types to aggregate
在此之前我检查了 dtype
Right before this I check dtype
print(type(df['price'][0]))
<class 'decimal.Decimal'>
我是这个图书馆和货币处理的新手,也许 Decimal 不是正确的选择?我该怎么办?
I'm new to this library and money processing, maybe Decimal is not the right choice for this? What should I do?
如果我将此列转换为
一切正常.
If I cast this column to <class 'numpy.float64'>
everything works.
更新:目前我正在使用这种方法
Update: For now I'm using this method
d.Decimal("%0.2f" % float(d.Decimal("1.04")))
Decimal('1.04')
来自这个问题
推荐答案
我们遇到了类似的问题,最好的办法是将其乘以 100 并将其表示为整数
(并使用/100 打印/外部选项).
它将导致快速精确计算(1 + 2 == 3 不像 0.1 + 0.2 != 0.3)
We had a similar problem, the best idea was to multiply it by 100 and represent it as an integer
(and use /100 for print/external options).
It will result in fast exact computations (1 + 2 == 3 unlike 0.1 + 0.2 != 0.3)
这篇关于什么 dtype 用于 pandas 数据框中的货币表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!