4

An answer I gave earlier raised a question for me: Is it possible to reference a view or slice of a numpy array without repeating a bunch of brackets?

For instance, in the answer I used s=np.argsort(u) and then did all my calculations on a 'virtually' sorted u[s]. I've had situations where I then needed a boolean mask of that array, giving something akin to u[s][mask]. For bigger data I might have a mask of a mask of a mask . . . until things start to look like the end of an episode of Scooby Doo.

But if I assign that array to a variable b=a[s][mask] and change b, a does not change, so I end up carrying a pile of brackets through my calculations. I've tried various arrangements of uv=u.view()[s] but it seems .view() only makes a view of the whole array. Is there another method I am missing?

1
  • The issue is [mask]. Since it makes an arbitrary subset of the array a, it always returns a new array, not a view. Can you avoid making a mask in the first place? Commented Dec 14, 2016 at 8:27

1 Answer 1

2

You may not be able to solve the simple case of u[s] but in more complex cases like u[s][mask] you can:

t = s[mask]
u[t] # same as u[s][mask]

That is, you can simplify your mask to a single variable, but you may not be able to get rid of it completely, unless perhaps you want to write your own wrapper class with __getitem__ and __setitem__.

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

2 Comments

But if I only have masks? I guess I could do t=np.indices(u.shape)[mask1][mask2][mask3]. I assume it ends up being the same problem pandas has where at some layer of abstraction it get tough to tell the difference between a slice and a copy without something like .loc to differentiate
@DanielForsman: Yeah. In your question you mentioned s=np.argsort(u) which is not a mask, but an array of indices. I worked from that assumption. If you have lots of masks you can compose them and just use the composed version on the original array.

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.