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
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