约束数组的值

时间:2012-06-08 13:08:08

标签: python numpy

我正在尝试约束numpy数组的值,以便在-0.5和0.5之间没有值。所以,如果我有一个数组形状(6,2),其值如下:

array([[  0.49873803,  -1.66316398],
       [ -0.36091764,   2.0635736 ],
       [ -1.09922111,  -2.49380792],
       [  0.92724579,  -5.19540319],
       [  1.49726584,  -0.22718924],
       [ 60.        ,  60.        ]])

如何更改来自-0.5 - >的值的numpy? 0.0为-0.5,和 从0.5 - > 0.0为0.5,以便示例数组为:

array([[  0.5,  -1.66316398],
       [ -0.5,   2.0635736 ],
       [ -1.09922111,  -2.49380792],
       [  0.92724579,  -5.19540319],
       [  1.49726584,  -0.5],
       [ 60.        ,  60.        ]])

我尝试使用np.clip但是没有用,或者我无法理解,所以我在这里!

2 个答案:

答案 0 :(得分:6)

对于a,只需运行:

a[( 0.  <= a) & (a < 0.5)] =  0.5
a[(-0.5 <  a) & (a < 0. )] = -0.5

或简单地说:

np.putmask(a, np.abs(a) < .5, np.sign(a) * .5)

可以根据您的需要调整第一个来处理0.。第二个将它留给0.

答案 1 :(得分:-1)

您是否尝试过遍历数组?

i = 0
j = 0

while ( i < len(A)):
    while (j < len(i)):
        if  -0.5 <= A[i][j] <= 0:
            A[i][j] = -0.5
        if  0 <= A[i][j] <= 0.5:
            A[i][j] = 0.5
        j = j + 1

    i =  i +1

或类似的东西......如果语法不正确,请原谅我......