Home > database >  pandas: round up to closet float number defined by user
pandas: round up to closet float number defined by user

Time:08-24

I have one array which contains continuous values. I need to round up those values to the closet float value. ex: 32.25 to 32.50 , 30.29 to 30.50, 33.75 to 34.00. In short: if it is from .1 to .49 round up to .50 and if it is from .51 to .99 round up to .00. How can I do it. Thank you in advance.

array([32.5 , 32.49, 32.48, 32.47, 32.46, 32.45, 32.44, 32.43, 32.42,
       32.41, 32.4 , 32.39, 32.38, 32.37, 32.36, 32.35, 32.34, 32.33,
       32.32, 32.31, 32.3 , 32.29, 32.28, 32.27, 32.26, 32.25, 15.75,
       15.76, 15.77, 15.78, 15.79, 15.8 , 15.81, 15.82, 15.83, 15.84,
       15.85, 15.86, 15.87, 15.88, 15.89, 15.9 , 15.91, 15.92, 15.93,
       15.94, 15.95, 15.96, 15.97, 15.98, 15.99, 16.  , 16.01, 16.02,
       16.03, 16.04, 16.05, 16.06, 16.07, 16.08, 16.09, 16.1 , 16.11,
       16.12, 16.13, 16.14, 16.15, 16.16, 16.17, 16.18, 16.19, 16.2 ,
       16.21, 16.22, 16.23, 16.24, 16.25, 16.26, 16.27, 16.28, 16.29,
       16.3 , 16.31, 16.32, 16.33, 16.34, 16.35, 16.36, 16.37, 16.38,
       16.39, 16.4 , 16.41, 16.42, 16.43, 16.44, 16.45, 16.46, 16.47,
       16.48, 16.49, 16.5 , 25.25, 25.5 , 25.51, 25.52, 25.53, 25.54,
       25.55, 25.56, 25.57, 25.58, 25.59, 25.6 , 25.61, 25.62, 25.63,
       25.64, 25.65, 25.66, 25.67, 25.68, 25.69, 25.7 , 25.71, 25.72,
       25.73, 25.74, 26.  , 26.01, 26.02, 26.03, 26.04, 26.05, 26.06,
       26.07, 26.08, 26.09, 26.1 , 26.11, 26.12, 26.13, 26.14, 26.15,
       26.16, 26.17, 26.18, 26.19, 26.2 , 26.21, 26.22, 26.23, 26.24,
       26.25, 26.26, 26.27, 26.28, 26.29, 26.3 , 26.31, 26.32, 26.5 ,
       26.49, 26.48, 26.47, 26.46, 26.45, 26.44, 26.43, 26.42, 26.41,
       26.4 , 26.39, 26.38, 26.37, 26.36, 26.35, 26.34, 26.33, 28.5 ,
       28.51, 28.52, 28.53, 28.54, 28.55, 28.56, 28.57, 28.58, 28.59,
       28.6 , 28.61, 28.62, 28.63, 28.64, 28.65, 28.66, 30.5 , 30.49,
       30.48, 30.47, 30.46, 30.45, 30.44, 30.43, 30.42, 30.41, 30.4 ,
       30.39, 30.38, 30.37, 30.36, 30.35, 30.34, 30.33, 30.32, 30.31,
       30.3 , 30.29, 30.28, 30.27, 30.26, 30.25])

CodePudding user response:

Another solution:

import math
[math.modf(item)[1]   0.5  if (0.1 <= ( item % 1) <= 0.5) else math.modf(item)[1] for item in array]

CodePudding user response:

Did you not experiment with this? numpy is built for experimentation.

array = (array * 2   0.4999).round() / 2

CodePudding user response:

use the below code

round_off_values = np.round_(array, decimals = 1)
  • Related