1

Trying to slice and average a numpy array multiple times, based on an integer mask array:

i.e.

import numpy as np

data = np.arange(11)
mask = np.array([0, 1, 1, 1, 0, 2, 2, 3, 3, 3, 3])

results = list()
for maskid in range(1,4):
    result = np.average(data[mask==maskid])
    results.append(result)
output = np.array(result)

Is there a way to do this faster, aka without the "for" loop?

1 Answer 1

1

One approach using np.bincount -

np.bincount(mask, data)/np.bincount(mask)

Another one with np.unique for a generic case when the elements in mask aren't necessarily sequential starting from 0 -

_,ids, count = np.unique(mask, return_inverse=1, return_counts=1)
out = np.bincount(ids, data)/count
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.