Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What dtype to use for money representation in pandas dataframe?

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.

My Try: Decimal module

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')

I get

pandas.core.groupby.DataError: No numeric types to aggregate

Right before this I check dtype

print(type(df['price'][0]))
<class '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')

From this question

like image 410
userqwerty1 Avatar asked Apr 09 '15 09:04

userqwerty1


1 Answers

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)

like image 79
Alex Ozerov Avatar answered Sep 22 '22 20:09

Alex Ozerov