2011-01-07 8 views

risposta

7
import numpy as np 

a = np.array([[1, 5, 6], 
       [2, 4, 1], 
       [3, 1, 5]]) 

np.ma.MaskedArray(a, mask=(np.ones_like(a)*(a[:,0]==1)).T) 

# Returns: 
masked_array(data = 
[[-- -- --] 
[2 4 1] 
[3 1 5]], 
      mask = 
[[ True True True] 
[False False False] 
[False False False]]) 
2

È possibile creare la maschera desiderata

mask = numpy.repeat(a[:,0]==1, a.shape[1]) 

e la matrice mascherato da

masked_a = numpy.ma.array(a, mask=numpy.repeat(a[:,0]==1, a.shape[1])) 
+0

Grazie per la risposta Sven! Sono nuovo di numpy e non ero a conoscenza del metodo di ripetizione. Lo cercherò. – Curious2learn

0

Si potrebbe semplicemente creare una maschera vuota e quindi utilizzare Numpy-trasmissione (come @eumiro mostrato) ma utilizzando l'operatore "or" di bit e di elemento |:

>>> a = np.array([[1, 5, 6], [2, 4, 1], [3, 1, 5]]) 

>>> mask = np.zeros(a.shape, bool) | (a[:, 0] == 1)[:, None] 

>>> np.ma.array(a, mask=mask) 
masked_array(data = 
[[-- -- --] 
[2 4 1] 
[3 1 5]], 
      mask = 
[[ True True True] 
[False False False] 
[False False False]], 
     fill_value = 999999) 

Un ulteriore spiegazione si morse:

>>> # select first column 
>>> a[:, 0] 
array([1, 2, 3]) 

>>> # where the first column is 1 
>>> a[:, 0] == 1 
array([ True, False, False], dtype=bool) 

>>> # added dimension so that it correctly broadcasts to the empty mask 
>>> (a[:, 0] == 1)[:, None] 
array([[ True], 
     [False], 
     [False]], dtype=bool) 

>>> # create the final mask 
>>> np.zeros(a.shape, bool) | (a[:, 0] == 1)[:, None] 
array([[ True, True, True], 
     [False, False, False], 
     [False, False, False]], dtype=bool) 

Un altro vantaggio di questo approccio è che non ha bisogno di utilizzare moltiplicazioni potenzialmente costosi o np.repeat quindi dovrebbe essere abbastanza veloce.