有沒有更優雅的方式將值帶入 0-50 范圍內的 numpy 陣列中?
x = np.array([-5, 6, 24, 51, 50, 40])
array([-5, 6, 24, 51, 50, 40])
x = np.where(x < 0, 0, x)
x = np.where(x > 50, 50, x)
array([ 0, 6, 24, 50, 50, 40])
uj5u.com熱心網友回復:
In [49]: x = np.array([-5, 6, 24, 51, 50, 40])
幾個選擇:
In [50]: np.clip(x,0,50)
Out[50]: array([ 0, 6, 24, 50, 50, 40])
In [52]: np.minimum(np.maximum(x,0),50)
Out[52]: array([ 0, 6, 24, 50, 50, 40])
uj5u.com熱心網友回復:
剛剛發現有https://numpy.org/doc/stable/reference/generated/numpy.clip.html#numpy.clip
np.clip(x, 0, 50)
array([ 0, 6, 24, 50, 50, 40])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/420068.html
標籤:
