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).

Leave a Comment

tech