numpy divide along axis

For the specific example you've given: dividing an (l,m,n) array by (m,) you can use np.newaxis:

a = np.arange(1,61, dtype=float).reshape((3,4,5)) # Create a 3d array 
a.shape                                           # (3,4,5)

b = np.array([1.0, 2.0, 3.0, 4.0])                # Create a 1-d array
b.shape                                           # (4,)

a / b                                             # Gives a ValueError

a / b[:, np.newaxis]                              # The result you want 

You can read all about the broadcasting rules here. You can also use newaxis more than once if required. (e.g. to divide a shape (3,4,5,6) array by a shape (3,5) array).

From my understanding of the docs, using newaxis + broadcasting avoids also any unecessary array copying.

Indexing, newaxis etc are described more fully here now. (Documentation reorganised since this answer first posted).


I think you can get this behavior with numpy's usual broadcasting behavior:

In [9]: a = np.array([[1., 2.], [3., 4.]])

In [10]: a / np.sum(a, axis=0)
Out[10]:
array([[ 0.25      ,  0.33333333],
       [ 0.75      ,  0.66666667]])

If i've interpreted correctly.

If you want the other axis you could transpose everything:

> a = np.random.randn(4,3).transpose()
> norms = np.apply_along_axis(np.linalg.norm,0,a)
> c = a / norms
> np.apply_along_axis(np.linalg.norm,0,c)
array([ 1.,  1.,  1.,  1.])