2

I have a numpy matrix A of shape [n,m] and an array b of length n. What I need is to take sum of b[i] least elements of the i'th row of A. So the code might look like this:

A = np.array([[1,2,3],
              [4,5,6],
              [7,8,9]])

b = np.array([2,3,1])

sums = magic_function() #sums = [3, 15, 7]

I've considered np.apply_along_axis() function but it seems that your function can only depend on the row itself in this case.

2
  • Is A sorted by column? Commented Nov 5, 2017 at 13:05
  • In general case no. Commented Nov 5, 2017 at 13:34

1 Answer 1

5

Vectorized approach making use of NumPy broadcasting to create the mask of valid ones along each row and then perform sum-reduction -

mask = b[:,None] > np.arange(A.shape[1])
out = (A*mask).sum(1)

Alternatively, with np.einsum to get the reduction -

out = np.einsum('ij,ij->i',A,mask)

We can also use np.matmul/@ notation on Python 3.x -

out = (A[:,None] @ mask[...,None]).squeeze()
Sign up to request clarification or add additional context in comments.

1 Comment

I like how there's always an einsum solution in your answers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.