newX
and breaks
are numpy ndarray of shape (24000L,) and (7L,) respectively. newX is within range of (0,9). yvals
is a lookup table based on breaks segmented into 10000 (nsegs) samples called xvals
(not used here).
deltaX=(breaks[-1]-breaks[0])/nsegs
xvals=[x+i*deltaX for i in range(nsegs+1)]
Both breaks and yvals are monotonically increasing. Basically, I want yvals[0] to be returned when newX value is less than the breaks[0], and yvals[-1] when newX value is higher than breaks[-1]. For other values I want it to generate an index for yvals corresponding to a point closest to xval (an example is shown below) When I do the following:
condlist=[newX<=breaks[0] , newX < breaks[-1] , newX >= breaks[-1]]
choicelist=[yvals[0] , yvals[((newX-breaks[0]))/deltax.astype(int).item()] , yvals[-1]]
ans = np.select(condlist,choicelist)
I get the error in the choicelist line -
ValueError: can only convert an array of size 1 to a Python scalar
How can I fix this?
No need for numpy.select here, your goal can be simply stated
choicelist = yVals[ix]
where ix is an array of indices to be computed. What I see is newX being transformed linearly, rounded to integers, and clipped so that indices do not go beyond the range 0...len(yVals)-1. All this is expressed by
ix = np.clip(np.around((newX-breaks[0])/deltax).astype(int), 0, len(yVals)-1)
where
np.around((newX-breaks[0])/deltax)
rounds the result of computation to nearest integer. Without the rounding .astype(int) would floor it, which is less desirable.np.clip(..., 0, len(yVals)-1)
clips the results so that all indices are valid.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.