0

If I create a numpy array, and another to serve as a selective index into it:

>>> x
array([[ 2,  3,  4],
       [ 5,  6,  7],
       [ 6,  7,  8],
       [11, 12, 13]])

>>> nz
array([ True,  True, False,  True], dtype=bool)

then direct use of nz returns a view of the original array:

>>> x[nz,:]
array([[ 2,  3,  4],
       [ 5,  6,  7],
       [11, 12, 13]])

>>> x[nz,:] += 2
>>> x
array([[ 4,  5,  6],
       [ 7,  8,  9],
       [ 6,  7,  8],
       [13, 14, 15]])

however, naturally, an assignment makes a copy:

>>> v = x[nz,:]

Any operation on v is on the copy, and has no effect on the original array.

Is there any way to create a named view, from x[nz,:], simply to abbreviate code, or which I can pass around, so operations on the named view will affect only the selected elements of x?

2
  • 1
    The last assignment uses x.__getitem__(idx_tuple). x[nz,:]=value uses x.__setitem__(idx_tuple, value). So while both use [nz,:] the underlying indexing operation is different. The distinction between view and copy only applies to the get operation. You could pass a idx_tuple=(nz,slice(None)) around, but you still have to use the x[idx_tuple]=... syntax. Commented Apr 27, 2019 at 16:14
  • Thank you. I would have thought that qualifies as an answer.. but I'm new here. Commented Apr 27, 2019 at 16:48

1 Answer 1

1

Numpy has masked_array, which might be what you are looking for:

import numpy as np

x = np.asarray([[ 2,  3,  4],[ 5,  6,  7],[ 6,  7,  8],[11, 12, 13]])
nz = np.asarray([ True,  True, False,  True], dtype=bool)

mx = np.ma.masked_array(x, ~nz.repeat(3)) # True means masked, so "~" is needed
mx += 2

# x changed as well because it is the base of mx 
print(x)
print(x is mx.base)
Sign up to request clarification or add additional context in comments.

1 Comment

This is pretty much what I've been looking for There are some warnings..but my operations are nearly as simple as in the OP, not nested, shape-changing, or anything... I'll test first before accepting. (There may be room for further commentary)

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.