qff
qff

Reputation: 5902

How do I keep the mask when slicing a masked array in Numpy?

When I create a view of a Numpy masked array (via slicing) the mask is copied to the view -- so that updates to the view will not change the mask in the original (but will change the data in the original array).

What I want is to change both the original data and the original mask when updating the view.

From the Numpy documentation:

When accessing a slice, the output is a masked array whose data attribute is a view of the original data, and whose mask is either nomask (if there was no invalid entries in the original array) or a copy of the corresponding slice of the original mask. The copy is required to avoid propagation of any modification of the mask to the original.

Example

import numpy.ma as ma

orig_arr = ma.array([[11,12],[21,22]])
orig_arr[1,:] = ma.masked

print orig_arr
## Prints: [[11 12]
##          [-- --]]

view_arr = orig_arr[1,:]
print view_arr
## Prints: [-- --]

view_arr[:] = [31,32]
print view_arr
## Prints: [31 32]

print orig_arr
## Prints: [[11 12]
##          [-- --]]
print orig_arr.data[1,:]
## Prints: [31 32]

As you can see the data in the original array has been updated, but the mask hasn't.

How do I make updates in the view affect the mask in the original array?

Upvotes: 4

Views: 2136

Answers (1)

M.T
M.T

Reputation: 5231

Try turning off the mask in the view before changing the value

orig_arr = ma.array([[11,12],[21,22]])
orig_arr[1,:] = ma.masked

print orig_arr
## Prints: [[11 12]
##          [-- --]]

view_arr = orig_arr[1,:]
print view_arr
## Prints: [-- --]

view_arr.mask=False # or [True, False] 


view_arr[:] = [31,32] 
print view_arr
## Prints: [31 32] #or [-- 32]

print orig_arr
## Prints: [[11 12]
##          [31 32]] # or [-- 32]

Upvotes: 3

Related Questions