Reputation: 49
I have to round every element inside a numpy array only to .5 or .0 values. I know the np.arange()
method, however it is not useful in this specific task since I can only use it to set a precision equal to one.
Here there is an example of what I should do:
x = np.array([2.99845, 4.51845, 0.33365, 0.22501, 2.48523])
x_rounded = some_function(x)
>>> x_rounded
array([3.0, 4.5, 0.5, 0.0, 2.5])
Is there a built-in method to do so or I have to create it? If I should create that method, is there an efficient? I'm working on a big dataset, so I would like to avoid iterating over each element.
Upvotes: 3
Views: 1015
Reputation: 5000
import numpy as np
x = np.array([2.99845, 4.51845, 0.33365, 0.22501, 2.48523])
np.round(2 * x) / 2
Output:
array([3. , 4.5, 0.5, 0. , 2.5])
Upvotes: 12