I have a number of numpy
arrays a
,b
,c
, ... which all should be trimmed according to a boolean mask array keep
or re-arranged according to an index array indices
. Doing this on an individual array works find via arr = arr[keep]
, but is tedious. Therefore, I want to do this for all arrays via a loop, but the following fails
for arr in [a,b,c]:
arr = arr[keep]
for arr in [a,b,c]:
arr = arr[indices]
I noted that indexing works okay if I do arr[:] = arr[indices]
, even if the shapes of arr
and indices
are different (but agree in the first axis). But this won't work with masking. So how to do this generically (for either masking or indexing) with minimum copies?
For completeness, here is the test case
import numpy as np
a = np.random.random(5)
b = np.array([[1,-1],[2,-2],[3,-3],[4,-4],[4,-4]])
# first test with indexing (for sorting)
i = np.argsort(a)
B = b[i] # for testing purposes
print(B)
for arr in [a,b]:
arr = arr[i]
print(b) # should match B
# second test with boolean (for masking)
k = a < 0.5
B = b[k] # for testing purposes
print(B)
for arr in [a,b]:
arr = arr[k]
print(b) # should match B