0

Given the dataset below, I am trying to extract everything after the third decimal place in the price column (if there is nothing after the 2nd decimal place, it should obviously be 0). I currently do the following:

df['frac'] = df['price']*100 - (df['price']*100).astype(int)

which I think should do what I expect it to do but gives really weird answers (see the frac column below). For instance, take the second observation at 2018-01-02 09:30:38.883094. Here, 'frac' should be 0.0 since there is nothing after 2 decimal places. But this gives a really small value, which is messing up my subsequent analysis.

                            price          frac
datetime                                       
2018-01-02 09:30:38.753416  67.24  1.000000e+00
2018-01-02 09:30:38.883094  67.43  9.094947e-13
2018-01-02 09:30:38.896296  67.35  1.000000e+00
2018-01-02 09:31:35.753740  67.46  1.000000e+00
2018-01-02 09:31:39.555765  67.51  9.094947e-13
2018-01-02 09:32:02.493157  67.51  9.094947e-13
2018-01-02 09:32:30.623568  67.51  9.094947e-13
2018-01-02 09:32:30.623796  67.51  9.094947e-13
2018-01-02 09:32:30.623846  67.51  9.094947e-13
2018-01-02 09:32:30.623869  67.51  9.094947e-13

Can anyone explain why this happens and how do I circumvent this? My sense is that it has something to do with how Python deals with small numbers (but don't know the exact issue).

I also tried df['frac'] = 100*(df['price']%0.01) but it also gives the same error.

AYA
  • 21
  • 6
  • `9.094947e-13` is zero in your context, just round the values to the desired precision and you'll have 0. NB. this is not python specific but due to how binary coding of floating point number works, all computers would do the same ;) – mozway Jun 06 '22 at 06:03
  • Please see if this helps: import math price = 2.13556 decimals = 2 factor = 10.0 ** decimals print (round ( price - math.trunc(price * factor) / factor, 6)) Output : 0.00556 Hope this is what you want : df['frac'] = round ( df['price' ]- math.trunc(df['price']*factor)/factor, 6) – Vineesh Vijayan Jun 06 '22 at 06:16

0 Answers0