Reputation: 65
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:
tmp[:,2] = np.around(tmp[:,2],1)
But that's not what I want.
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
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
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