Linalg.norm does not accept axis argument

I am using Python 3 in Pyzo. Please could you tell me why the linalg.norm function does not recognize the axis argument.

This code:

c = np.array([[ 1, 2, 3],[-1, 1, 4]]) d=linalg.norm(c, axis=1) 

returns an error:

TypeError: norm () received an unexpected keyword argument 'axis'

+7
python numpy norm
source share
2 answers

linalg.norm does not accept the axis argument. You can get around this with:

 np.apply_along_axis(np.linalg.norm, 1, c) # array([ 3.74165739, 4.24264069]) 

Or, to be faster, do it yourself:

 np.sqrt(np.einsum('ij,ij->i',c,c)) # array([ 3.74165739, 4.24264069]) 

To sync:

 timeit np.apply_along_axis(np.linalg.norm, 1, c) 10000 loops, best of 3: 170 ยตs per loop timeit np.sqrt(np.einsum('ij,ij->i',c,c)) 100000 loops, best of 3: 10.7 ยตs per loop 
+10
source share

In numpy versions below 1.8 linalg.norm does not accept the axis argument, you can use np.apply_along_axis to get the desired result, as Warren Ukenser pointed out in the comment on the question.

 import numpy as np from numpy import linalg c = np.array([[ 1, 2, 3],[-1, 1, 4]]) d = np.apply_along_axis(linalg.norm, 1, c) 

Result:

 >>> d array([ 3.74165739, 4.24264069]) 
+4
source share

All Articles