This question already has answers here:

Replace all elements of Python NumPy Array that are greater than some value
(6个答案)
如果我有一个nxn numpy数组,如果有一个负数作为任何位置,有没有一种简单快捷的方法可以用0替换这个数字?
有点像
for item in array:
    if item <= 0:
        item = 0

最佳答案

您可以使用布尔掩码来屏蔽整个数组,这比像您现在这样迭代要高效得多:

In [41]:
array = np.random.randn(5,3)
array

Out[41]:
array([[-1.09127791,  0.51328095, -0.0300959 ],
       [ 0.62483282, -0.78287353,  1.43825556],
       [ 0.09558515, -1.96982215, -0.58196525],
       [-1.23462258,  0.95510649, -0.76008193],
       [ 0.22431534, -0.36874234, -1.46494516]])

In [42]:
array[array < 0] = 0
array

Out[42]:
array([[ 0.        ,  0.51328095,  0.        ],
       [ 0.62483282,  0.        ,  1.43825556],
       [ 0.09558515,  0.        ,  0.        ],
       [ 0.        ,  0.95510649,  0.        ],
       [ 0.22431534,  0.        ,  0.        ]])

10-02 07:35
查看更多