Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy set absolute value in place

You have an array A, and you want to turn every value in it as an absolute value. The problem is

numpy.abs(A)

creates a new matrix, and the values in A stay where they were. I find two ways to set put the absolute values back to A

A *= numpy.sign(A)

or

A[:] = numpy.abs(A)

Based on timeit test, their performance is almost the same enter image description here

Question:

Are there more efficient ways to perform this task?

like image 399
Tony Avatar asked Jan 25 '18 20:01

Tony


People also ask

How do you use absolute value in Numpy?

Get absolute values from a NumPy array To get their absolute values, we call the numpy. abs() function and pass in that array as an argument. As a result NumPy returns a new array, with the absolute value of each number in the original array.

How do you take the absolute value of an array?

Y = abs( X ) returns the absolute value of each element in array X . If X is complex, abs(X) returns the complex magnitude.


1 Answers

There's an out parameter, which updates the array in-place:

numpy.abs(A, out=A)

And also happens to be a lot faster because you don't have to allocate memory for a new array.

A = np.random.randn(1000, 1000)

%timeit np.abs(A)
100 loops, best of 3: 2.9 ms per loop

%timeit np.abs(A, out=A)
1000 loops, best of 3: 647 µs per loop
like image 188
cs95 Avatar answered Sep 25 '22 03:09

cs95