Home > Software design >  Normalize a Numpy array of 2D vector by a Pandas column of norms
Normalize a Numpy array of 2D vector by a Pandas column of norms

Time:02-18

I have a Numpy array of 2D coordinates :

uv = np.array([[u_1, v_1],
               [u_2, v_2],
               [u_3, v_3]])

I need to normalize it by a vector containing a list of norms for each vector stored as a Pandas Series:

L = pd.Series([L_1, L_2, L_3])

Expected result:

uv = np.array([[u_1 / L_1, v_1 / L_1],
               [u_2 / L_2, v_2 / L_2],
               [u_3 / L_3, v_3 / L_3]])

So, of course I can do it by slicing the vector:

uv[:,0] /= L
uv[:,1] /= L

But knowing Numpy, there should be a more efficient way to do it in one line and one loop over the data. What is it ?

np.multiply() does not have an axis argument and complains : operands could not be broadcast together with shapes (2816,2) (2816,).

CodePudding user response:

If both arrays are in numpy, you just need to Transpose it:

(uv.T/L).T

In the case of the question, as L is a Series, then:

(uv.T/L.to_numpy()).T

CodePudding user response:

The final solution is :

(uv.T / L.to_numpy()).T

It seems pandas.Series support scalar operations but need to be cast as explicit np.array to enable vector/matrices operations.

  • Related