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
Question:
Are there more efficient ways to perform this task?
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.
Y = abs( X ) returns the absolute value of each element in array X . If X is complex, abs(X) returns the complex magnitude.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With