Tony
Tony

Reputation: 1393

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?

Upvotes: 8

Views: 1597

Answers (1)

cs95
cs95

Reputation: 402363

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

Upvotes: 11

Related Questions