3

I have [6, -1, -3, -5]. I want to make the negative values positive, e.g. [6, 1, 3, 5]. Is there an easy way to do this?

Thank you so much, in advance!

2
  • 2
    numpy.abs should do it Commented Dec 17, 2021 at 3:20
  • On Python 2 and Python 3 you can convert any number to positive with abs(). You can convert int or float negative without numpy. Example : print(abs(-6)) show you : 6 Commented Dec 17, 2021 at 3:36

2 Answers 2

7

Simply use the builtin abs function:

>>> a = np.array( [6, -1, -3, -5])
>>> a
array([ 6, -1, -3, -5])

>>> abs(a)
array([6, 1, 3, 5])
Sign up to request clarification or add additional context in comments.

Comments

0

And if you are like me and swear by the name of list comprehension, try this:

abs_a = [-i if i <0 else i for i in a ] 

Where abs_a stands for the absolute value of a

1 Comment

I love list comprehension too... when I deal with lists! The question here is specifically about numpy. List comprehension are still pure python iterations. They are slower (more than 2 times even with the short example given. 100 times with more serious examples). And anyway, off topic when a numpy question is asked (your abs_a isn't even a ndarray).

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.