trippeljojo
trippeljojo

Reputation: 65

How to efficiently round only one column of numpy array to nearest 0.5?

Is there an efficient way of rounding only one column of a numpy array? I.e. I want the numbers to round to nearest 0.5 which can be done with round(number * 2.0) / 2.0.

Assuming, I have the numpy array tmp and I aim at rounding the third column. There are the following things, I tried:

  1. For just rounding to certain decimals, I could use
tmp[:,2] = np.around(tmp[:,2],1)

But that's not what I want.

  1. I define a function and try to apply along axis:
def roundToHalf(number):
   return round(number * 2.0) / 2.0

tmp[:,2] = np.apply_along_axis(roundToHalf,0,tmp[:,2])

or

tmp[:,2] = roundToHalf(tmp[:,2])

This doesn't work because I get an error:

*** TypeError: type numpy.ndarray doesn't define __round__ method

In the worst case, I would just go with a for loop. But I hope you guys can help me to find a smoother solution.

Upvotes: 1

Views: 1939

Answers (2)

Novice
Novice

Reputation: 915

The problem is that you wrote the function to handle a single number, not an array. You can use numpy's around to round an entire array. Your function would then be

import numpy as np
def roundToHalf(array):
   return np.around(array * 2.0) / 2.0

and if you input a numpy array it should work. Example below

In [24]: roundToHalf(np.asarray([3.6,3.8,3.3,3.1]))
Out[24]: array([3.5, 4. , 3.5, 3. ])

Upvotes: 1

Alexis Pister
Alexis Pister

Reputation: 499

You can apply np.vectorize() on your function roundToHalf(), for it to be appliable on a numpy array

roundToHalf_vect = np.vectorize(roundToHalf)
tmp[:,2] = roundToHalf_vect(tmp[:,2])

Upvotes: 0

Related Questions