Boosted_d16 Boosted_d16 - 1 year ago 89
Python Question

Python Pandas: why does np.round() rounds 14.50 down to 14?

I was surprised to learn that

np.round(item, decimals=0)
rounds
14.50
down to
14
. I understand this is linked to the number of decimal point but I'm not sure why?

How can I ensure that number like
14.50
is always rounded up
15
.

script

myval = 14.50
np.round(myval, decimals=0)


output

14.0

Answer Source

If you're using 2.x the default python round function should do what you want for positive floats.

   >>> round(14.5)
   15.0

   >>> round(14.49)
   14.0

Not sure what best practices are but this works for a dataframe and python 2.x:

df = pd.DataFrame([1.5,2.5,3.5])
rounded_df = df.applymap(round)

Note python 2.x's round rounds away from zero so it will round negative numbers down.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download