If I have an NxN numpy array and if there is a negative number as any position, is there a simple and quick way I can replace that number with a 0? something like
for item in array: if item <= 0: item = 0 You can mask the entire array by using a boolean mask, this will be much more efficient than iterating like you currently are:
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. ]]) Based on this SO answer, you can use numpy's builtin indexing for this.
arr[arr < 0] = 0
array[array <= 0 ] = 0should work also you say negative, shouldn't it bearray[array < 0] = 0rather than<=0?0with0. The only difference might be if the array hasfloats and some0have the "negative sign" while other have the positive sign, by assigning0you set all of them to the "positive sign", but I believe all the operations should work the same.<0and<=0with the negative statement irrespective of the end result, it's clear that<0means negative whilst<=0does not