pandas.DataFrame.round() gives somewhat unpredictable output on the below data frame. Can anyone please help me understand what is happening here?
df = pd.DataFrame([(61.21, 69.32), (65.1938, .67)], columns=['A', 'B'], dtype='float32') df.round(2) The above code outputs:
A B 0 61.209999 69.32 1 65.190002 0.67 Why does round(2) not truncate all but first 2 digits after decimal point? When I try the same with dtype='float64' it works and outputs below:
df.astype('float64').round(2) A B 0 61.21 69.32 1 65.19 0.67 Is there something about the values in the data frame?
I don't want to format the output as string (round(2).applymap('{:.2f}'.format)) to get the desired number of decimals. I want to know why the columns are giving different number of digits after the decimal point.
I am using pandas version '0.24.1'.
float64values also differ from the decimal results you see and are expecting (but should not). Instead of 65.19, the actual value is 65.18999999999999772626324556767940521240234375, but the software is not showing you enough digits to see that. It is impossible to round binary floating-point numbers to two decimal places (except for .00, .25, .50, and .75) because binary floating-point numbers do not have decimal places. The values 65.19 and 61.21 are simply not representable in binary floating-point.float64format, the differences are small enough that you cannot see them in the digits the software shows you. In thefloat32format, they are (or at least some of them are) large enough that you see them.x == yis not a continuous function; it has a discontinuity at x = y. Generally, you should not be using floating-point arithmetic in situations where you need to test numbers for equality (and you should not attempt workarounds to make it work in such situations).