Numpy: Divide each row by a vector element Numpy: Divide each row by a vector element arrays arrays

Numpy: Divide each row by a vector element


Here you go. You just need to use None (or alternatively np.newaxis) combined with broadcasting:

In [6]: data - vector[:,None]Out[6]:array([[0, 0, 0],       [0, 0, 0],       [0, 0, 0]])In [7]: data / vector[:,None]Out[7]:array([[1, 1, 1],       [1, 1, 1],       [1, 1, 1]])


As has been mentioned, slicing with None or with np.newaxes is a great way to do this.Another alternative is to use transposes and broadcasting, as in

(data.T - vector).T

and

(data.T / vector).T

For higher dimensional arrays you may want to use the swapaxes method of NumPy arrays or the NumPy rollaxis function.There really are a lot of ways to do this.

For a fuller explanation of broadcasting, seehttp://docs.scipy.org/doc/numpy/user/basics.broadcasting.html


Pythonic way to do this is ...

np.divide(data.T,vector).T

This takes care of reshaping and also the results are in floating point format.In other answers results are in rounded integer format.

#NOTE: No of columns in both data and vector should match