1

I'm creating a dataframe in Pandas by reading it from a csv file. The dataframe contains several float values. When I iterrated through my dataframe using itertuples, one float value changed from 2.3 to 2.2999999999999998. First I thought this may occure because dataformats change from dataframe to tuple but the value is stored as float both in the dataframe and the tuple.

So my question is: Why does this happen?

print(dfAll) 
speed=dfAll['speed']
for value in motion:
   print(type(value))
for t in dfAll.itertuples():
   print(type(t.speed))
   print(t)

phase  motion  speed  attention shape_speed shape_combination  fail
0      1      80    1.7         90          up                up     0
1      1      89    1.5         85        same              same     0
2      1      75    2.3         75        down              down     0
3      1      82    2.5         80        same              same     0
4      1      30    0.0          0           0                 0     1
<type 'numpy.float64'>
<type 'numpy.float64'>
<type 'numpy.float64'>
<type 'numpy.float64'>
<type 'numpy.float64'>
<type 'numpy.float64'>
Pandas(Index=0, phase=1, motion=80, speed=1.7, attention=90, shape_speed=u'up', shape_combination=u'up', fail=0)
<type 'numpy.float64'>
 Pandas(Index=1, phase=1, motion=89, speed=1.5, attention=85, shape_speed=u'same', shape_combination=u'same', fail=0)
<type 'numpy.float64'>
 Pandas(Index=2, phase=1, motion=75, speed=2.2999999999999998, attention=75, shape_speed=u'down', shape_combination=u'down', fail=0)
<type 'numpy.float64'>
Pandas(Index=3, phase=1, motion=82, speed=2.5, attention=80,   shape_speed=u'same', shape_combination=u'same', fail=0)
<type 'numpy.float64'>
Pandas(Index=4, phase=1, motion=30, speed=0.0, attention=0, shape_speed=u'0', shape_combination=u'0', fail=1)
Axolotl
  • 95
  • 1
  • 2
  • 7
  • are you sure this isn't just float imprecision? – EdChum Feb 07 '17 at 15:05
  • this is expected behavior due to representing floats in binary – Mohammad Athar Feb 07 '17 at 15:08
  • yes this could be, I'm not familiar with floats. Appeared strange to me, because I'm not doing anything with the values – Axolotl Feb 07 '17 at 15:10
  • Possible duplicate of [Unexpected behavior of floating point numbers in C](http://stackoverflow.com/questions/25726701/unexpected-behavior-of-floating-point-numbers-in-c) – Mohammad Athar Feb 07 '17 at 15:11
  • The numbers stored in your machine aren't changing; this simply has to do with how they're represented. `2.3` and `2.2999999999999998` are two different representations of the exact same actual value. (Try `2.2999999999999998 == 2.3` at a Python prompt.) The *actual* value stored in the machine is `2.29999999999999982236431605997495353221893310546875`, which is rather long, so you can see why most tools choose to show a rounded representation rather than an exact one. – Mark Dickinson Feb 08 '17 at 13:54

0 Answers0