给定一个 numpy 数组,我想根据不等式替换它的值。例如,给定
x=np.array([0.3,7,8,-5.5,1,0.1])
我想将小于0的值替换为0,0到5之间的值替换为1,其余的替换为2。所以我想得到:
x=np.array([1,2,2,0,1,1])
我可以使用 pandas.cut
来做到这一点,如下所示:
pandas.cut(pandas.DataFrame(x).iloc[:,0],[-np.inf,0,5,np.inf],labels=[0,1,2],right=False)
但我想知道是否有更直接的方法使用 numpy 本身来做到这一点。请注意,我可能有 3 个以上的类别,这就是为什么我一直在寻找更系统的东西,其行为类似于 pandas.cut
。
最佳答案
利用完美设置 np.searchsorted
-
np.searchsorted([0,5],x)
这是可扩展的,可以合并通用数量的 bin 元素。因此,一般来说 -
bins = [0,5]
out = np.searchsorted(bins,x)
样本运行-
In [46]: x
Out[46]: array([ 0.3, 7. , 8. , -5.5, 1. , 0.1])
In [47]: np.searchsorted([0,5],x)
Out[47]: array([1, 2, 2, 0, 1, 1])
In [55]: np.searchsorted([0,2,5],x)
Out[55]: array([1, 3, 3, 0, 1, 1])
In [60]: np.searchsorted([0,2,5,7],x)
Out[60]: array([1, 3, 4, 0, 1, 1])
关于python - 基于不等式替换 numpy 数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44970593/