Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python round does not return integer

I wrote the following piece of code to round off the floating values in the dataframe a

a = pd.DataFrame([[1.2,3.4],[1.4,4.6]])
a = a.apply(round)

But the output I get is as follows:

    0   1
0   1.0 3.0
1   1.0 5.0

Why does the function return rounded off floating point values and not an integer?

Also, on being applied as follows, the behaviour is different:

round(0.5)
>>0
x= [1.4,2.5,3.6]
list(map(round,x))

>>[1, 2, 4]

Why this anomaly?

like image 678
paradocslover Avatar asked Sep 16 '25 23:09

paradocslover


1 Answers

apply calls the round function on each column in succession. DataFrame columns are Series objects, and these have a __round__ dunder method defined on them with a slightly different behaviour. This is actually what round calls when called on the Series.

round(a[0])

0    1.0
1    1.0
Name: 0, dtype: float64

# Same as,
a[0].__round__()

0    1.0
1    1.0
Name: 0, dtype: float64

Contrast this with the typical behaviour for python round on scalars:

round(1.5)
# 2

 # Same as,
(1.5).__round__()
# 2

If you want the same behaviour, use applymap.

a.applymap(round)

   0  1
0  1  3
1  1  5

Which applies round on each element (scalar), rounding down to an integer.

Or, my recommended solution,

a.round().astype(int)

   0  1
0  1  3
1  1  5

Beware that this will not typecast columns containing missing data (NaNs).

like image 124
cs95 Avatar answered Sep 19 '25 14:09

cs95