I have a list of revenue charges that I need to round up or down to the nearest bin.
For example, if the only products sold cost the following:
import numpy as np
bins = np.array([9.95,19.95,79.95])
and I have a few charges like this:
x = np.array([6.68, 9.20, 12.5, 18.75, 21.59])
I followed this example, which is definitely the closest solution:
y = np.take(bins,np.digitize(x,bins))
I thought leaving the right=
parameter to the default for np.digitize
would accomplish what I needed, but the results are still rounded up:
In [10]: y
Out[10]: array([ 9.95, 9.95, 19.95, 19.95, 79.95])
In my particular case, I need to round up or down to the nearest bin. For example, the $12.50 charge is only $2.55 away from $9.95, but the chosen option, $19.95, is $7.45 away.
EDIT
While one answer in the solution I linked to can round both up/down, it appears that method can return inconsistent results, hence this new post.
If you want to round to certain values you need to split at their midpoints. Like so:
import numpy as np
bins = np.array([9.95,19.95,79.95])
centers = (bins[1:]+bins[:-1])/2
x = np.array([6.68, 9.20, 12.5, 18.75, 21.59])
res = bins[np.digitize(x, centers)]
Gives
array([ 9.95, 9.95, 9.95, 19.95, 19.95])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With