Doing it manually might be fastest (although there's always some neat trick someone posts I didn't think of):
In [75]: from numpy import random, array
In [76]: from numpy.linalg import norm
In [77]:
In [77]: A = random.rand(1000,3)
In [78]: timeit normedA_0 = array([norm(v) for v in A])
100 loops, best of 3: 16.5 ms per loop
In [79]: timeit normedA_1 = array(map(norm, A))
100 loops, best of 3: 16.9 ms per loop
In [80]: timeit normedA_2 = map(norm, A)
100 loops, best of 3: 16.7 ms per loop
In [81]: timeit normedA_4 = (A*A).sum(axis=1)**0.5
10000 loops, best of 3: 46.2 us per loop
This assumes everything's real. Could multiply by the conjugate instead if that's not true.
Update: Eric's suggestion of using math.sqrt
won't work -- it doesn't handle numpy arrays -- but the idea of using sqrt instead of **0.5
is a good one, so let's test it.
In [114]: timeit normedA_4 = (A*A).sum(axis=1)**0.5
10000 loops, best of 3: 46.2 us per loop
In [115]: from numpy import sqrt
In [116]: timeit normedA_4 = sqrt((A*A).sum(axis=1))
10000 loops, best of 3: 45.8 us per loop
I tried it a few times, and this was the largest difference I saw.
numpy.array
is different from thearray
class in Python. I assume that you want answers related tonumpy.array
? – Capillaceousaxis
argument:norm(A, axis=1)
. – Imbalance