1

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 ?

1
  • if the value is -1.23 you don't want to replace it? Commented Jun 16, 2016 at 15:21

1 Answer 1

4

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])
Sign up to request clarification or add additional context in comments.

2 Comments

My data is numpy array. I want to replace all the elements starts with "- 0.0" not " -0.5". But your answer helps to replace only "-99" , which is negative integer.
What I posted is just an example, you can have the array filled with floats and it'll still work. And you can specify any interval in masked_where or use masked_inside which is a shortcut like this c = numpy.ma.masked_inside(x, 0, -0.1, copy=False)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.