0

In Numpy I have a boolean array of equal length of a matrix. I want to run a calculation on the matrix elements that correspond to the boolean array. How do I do this?

a: [true, false, true]
b: [[1,1,1],[2,2,2],[3,3,3]]

Say the function was to sum the elements of the sub arrays

index 0 is True: thus I add 3 to the summation (Starts at zero)

index 1 is False: thus summation remains at 3

index 2 is True: thus I add 9 to the summation for a total of 12

How do I do this (the boolean and summation part; I don't need how to add up each individual sub array)?

1 Answer 1

2

You can simply use your boolean array a to index into the rows of b, then take the sum of the resulting (2, 3) array:

import numpy as np

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

# index rows of b where a is True (i.e. the first and third row of b)
print(b[a])
# [[1 1 1]
#  [3 3 3]]

# take the sum over all elements in these rows
print(b[a].sum())
# 12

It sounds like you would benefit from reading the numpy documentation on array indexing.

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.