Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Norm along row in pandas

Tags:

I have a pandas Dataframe with N columns representing the coordinates of a vector (for example X, Y, Z, but could be more than 3D).

I would like to aggregate the dataframe along the rows with an arbitrary function that combines the columns, for example the norm: (X^2 + Y^2 + Y^2).

I want to do something similar to what is done here and here and here but I want to keep it general enough that the number of columns can change and it behaves like

DataFrame.mean(axis = 1) 

or

DataFrame.sum(axis = 1) 
like image 793
Fra Avatar asked Aug 30 '13 02:08

Fra


2 Answers

I found a faster solution than what @elyase suggested:

np.sqrt(np.square(df).sum(axis=1)) 
like image 200
Fra Avatar answered Oct 11 '22 18:10

Fra


Numpy provides norm... Use:

np.linalg.norm(df[['X','Y','Z']].values,axis=1) 
like image 40
ntg Avatar answered Oct 11 '22 18:10

ntg