Kevin Choi
Kevin Choi

Reputation: 765

numpy apply_along_axis computation on multidimensional data

I am translating a J language code into Python, but the way of python's apply function seems little unclear to me...

I currently have a (3, 3, 2) matrix A, and a (3, 3) matrix B.

I want to divide each matrix in A by rows in B:

A = np.arange(1,19).reshape(3,3,2)
array([[[ 1,  2],
        [ 3,  4],
        [ 5,  6]],

       [[ 7,  8],
        [ 9, 10],
        [11, 12]],

       [[13, 14],
        [15, 16],
        [17, 18]]])
B = np.arange(1,10).reshape(3,3)
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

That is the result would be like

      1 2
    1.5 2
1.66667 2

   1.75 2
    1.8 2
1.83333 2

1.85714 2
  1.875 2
1.88889 2

for the first matrix of the result, the way I want to compute is the following:

 1/1  2/1
 3/2  4/2
 5/3  6/3

I have tried

np.apply_along_axis(np.divide,1,A,B)

but it says

operands could not be broadcast together with shapes (10,) (10,10,2) 

Any advice? Thank you in advance = ]

ps. the J code is

A %"2 1 B 

This means "divide each matrix("2) from A by each row ("1) from B"

or just simply

A % B

Upvotes: 2

Views: 359

Answers (1)

pkapka
pkapka

Reputation: 5346

Broadcasting works if the trailing dimensions match or are one! So we can basically add a dummy dimension!

import numpy as np
A = np.arange(1,19).reshape(3,3,2)
B = np.arange(1,10).reshape(3,3)
B = B[...,np.newaxis] # This adds new dummy dimension in the end, B's new shape is (3,3,1)
A/B

array([[[1.        , 2.        ],
        [1.5       , 2.        ],
        [1.66666667, 2.        ]],

    [[1.75      , 2.        ],
        [1.8       , 2.        ],
        [1.83333333, 2.        ]],

    [[1.85714286, 2.        ],
        [1.875     , 2.        ],
        [1.88888889, 2.        ]]])

Upvotes: 2

Related Questions