将多个整数向量的数组更改为Numpy中每个向量的单个值

时间:2016-10-13 19:52:59

标签: python numpy

我在下面有一个数组,我想让每一行随机地有一个1或全部为0,但只有当前的1个值可以转换为0.我在下面检查是否会通过看到这样做如果行中有一个1并且总和值更大或者=到0.我希望有一个简单的方法来做到这一点,目前正在逃避我。

A = np.array([
        [   0   ,   1   ,   1   ,   0   ,   1   ]   ,
        [   1   ,   0   ,   0   ,   1   ,   1   ]   ,
        [   0   ,   0   ,   1   ,   0   ,   0   ]   ,
        [   0   ,   1   ,   0   ,   0   ,   1   ]   ,
        [   1   ,   0   ,   0   ,   0   ,   0   ]   ,
        [   0   ,   0   ,   1   ,   1   ,   0   ]   ,
        [   0   ,   0   ,   0   ,   0   ,   0   ]   ,
        [   1   ,   0   ,   1   ,   0   ,   0   ]   ,
        [   1   ,   0   ,   1   ,   1   ,   1   ]   ,
        [   0   ,   0   ,   1   ,   1   ,   0   ]   ,
        [   0   ,   1   ,   0   ,   1   ,   0   ]   ,
        [   0   ,   1   ,   0   ,   0   ,   1   ]   ,
        [   0   ,   0   ,   1   ,   1   ,   0   ]   ,
        [   0   ,   1   ,   1   ,   0   ,   1   ]   ,
        [   0   ,   0   ,   1   ,   0   ,   0   ]   ])

if np.any(A[0] == 1)==True and np.sum(A[0])>=0:
    change row to all 0's randomly or keep one of the existing 1 values randomly.  Ideally, if it could do it to the whole array, it would be very useful, but row by row is fine.   

1 个答案:

答案 0 :(得分:0)

您可以在每行中随机选择要保留的列:

m, n = A.shape
J = np.random.randint(n, size=m)

您可以使用它们来创建新阵列:

I = np.arange(m)
B = np.zeros_like(A)
B[I,J] = A[I,J]

或者,如果您想修改A,例如使用位移:

I = np.arange(m)
A[I,J] <<= 1
A >>= 1