1

For the following array:

array = [
  [1, 5, 6, 8, 10, 3],
  [3, 2, 4, 9, 11, 7],
  [8, 0, 9, 6, 23, 4]
]

How could we sum the elements (per row) as indicated by these indices:

indices = [
  [2, 4, 5],
  [1, 3],
  [4]
]

that is to say that:

  • for the first row only the values on indices [2, 4, 5] will be considered when summing up -> (6 + 10 + 3)
  • for the second row only the values on indices [1, 3] will be considered when summing up -> (2 + 9)
  • and so on

Output:

array([19, 11, 23])

The output has the same shape as if we did array.sum(axis=1) but not every value is included. Instead, the participants of each row are determined by the indices array.

I have thought of creating a mask for that purpose, but I did not know how to pass the indices to it.

2
  • How about a new array with 0 for the values you don't want to sum? Commented Nov 5, 2022 at 20:10
  • @hpaulj Could you please illustrate this? Commented Nov 5, 2022 at 20:14

1 Answer 1

1

Try this:

arr = np.array(array)
out = np.array([arr[idx, ind].sum() for idx, ind in enumerate(indices)])
out

Output : array([19, 11, 23])

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.