Reputation: 873
Let's say I have a matrix
x = [[0.708, 0.000, -0.070],
[-0.004, 0.561, -0.088 ],
[ 0.001, -0.001 -0.023]]
I want to replace all the negative values if it begins -0.0
with 0.
Is there any way to do it python. Since my matrix is really big, it also need to be computationally efficient ?
Upvotes: 1
Views: 1030
Reputation: 727
Easiest solution I would suggest is using numpy for handling any matrix operations so you won't have to reimplement the wheel. Maybe it would be worth looking into numpy masking operations, like masked_where
I'm not saying this is the most efficient solution, really don't know what you consider big matrix and what sort of efficiency you need, I would probably try several approaches, and compare them using profiler and decide which is best for you.
>>> import numpy
>>> x = numpy.array([1, 2, 3, -99, 5])
>>> c = numpy.ma.masked_where(x < 0, x, copy=False)
>>> c
masked_array(data = [1 2 3 -- 5],
mask = [False False False True False],
fill_value = 999999)
>>> x2 = c.filled(0)
>>> x2
array([1, 2, 3, 0, 5])
Upvotes: 4