Issue
Is there a more elegant way of setting an explicit rounding limit?
What I'm using:
arr= #original array
rnd_lim=1.7
rounded_arr=np.where(arr.__ge__(rnd_lim), arr,np.floor( arr))
rounded_arr=np.where(rounded_arr.__lt__(rnd_lim), rounded_arr,np.ceil(rounded_arr))
Input:
array([1.115, 1.722, 1.21 , 2. , 1.025, 2. , 1.269, 2. , 1.349,
1.952, 1.804, 1.871, 1.853, 1.992, 1.862, 2. , 1.45 , 2. ,
1.089, 1.464, 1.011, 1.371, 1.001, 1.611, 1.341, 1.174, 1.012,
1.076, 1.627, 1.266, 1.812, 2. , 1.031, 1.675, 1.273, 1.093,
2. , 1.874, 1.281, 1.974, 1.043, 1.526, 2. , 1.264, 1.153,
1.01 , 1.893, 1.988, 1.42 , 1.284, 1.727, 2. , 2. , 1.93 ,
1.789, 2. , 1.084, 1.984])
Output:
array([1., 2., 1., 2., 1., 2., 1., 2., 1., 2., 2., 2., 2., 2., 2., 2., 1.,
2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 2., 1., 1.,
1., 1., 2., 2., 1., 2., 1., 1., 2., 1., 1., 1., 2., 2., 1., 1., 2.,
2., 2., 2., 2., 2., 1., 2.])
Sub question: The method I am currently using only woks with sets of numbers with a range of 1. Is there a method that only checks the decimal place, and therefore also works with more disparate sets?
Solution
Use np.divmod
to separate the whole numbers and fractions in each element. Then round the fractional parts using your method and recombine:
>>> arr = np.array([0.6, 0.8, 1.6, 1.8, 2.6, 2.8])
>>> rnd_lim = 0.7
>>> whole, frac = np.divmod(arr, 1)
>>> rounded_fracs = np.where(frac.__ge__(rnd_lim), frac,np.floor(frac))
>>> rounded_fracs = np.where(rounded_fracs.__lt__(rnd_lim), rounded_fracs, np.ceil(rounded_fracs))
>>> rounded_fracs + whole
array([0., 1., 1., 2., 2., 3.])
Answered By - Woodford
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.